Как мне повысить скорость работы этого скрипта Python?Python

Программы на Python
Ответить
Anonymous
 Как мне повысить скорость работы этого скрипта Python?

Сообщение Anonymous »

Некоторое время назад я начал увлекаться гоночными симуляторами, но поскольку я сам не могу позволить себе руль, я искал способы его эмуляции и наткнулся на приложение, которое позволяет мне писать сценарии на Python с определенными библиотеками: https://andersmalmgren.github.io/FreePIE/.
Дело в том, что этот скрипт, который у меня есть, имеет тенденцию сильно лагать, например, когда я удерживаю X (клавиша для переключения между полным торможением и торможением всего лишь на мгновение). четверть) чем больше я его держу, тем больше он задерживается после того, как я отпускаю ключ, это также происходит, когда я использую ключ сцепления (C) и ключ «Плавный газ» (Z), я думаю, это связано с способ, которым я это запрограммировал (в основном спагетти, так как я не очень хорошо знаю Python), поэтому я подумал, что смогу получить помощь от этого форума, а также это мой первый раз, и это моя новая новая учетная запись, так что я мог бы что-то сделать здесь не так, но в любом случае вот код:

Код: Выделить всё

if starting:
system.setThreadTiming(TimingTypes.HighresSystemTimer)
system.threadExecutionInterval = 5

def set_button(button, key):
if keyboard.getKeyDown(key):
v.setButton(button, True)
else:
v.setButton(button, False)

def calculate_rate(max, time):
if time > 0:
return max / (time / system.threadExecutionInterval)
else:
return max

int32_max = (2 ** 14) - 1
activate = True
int32_min = (( 2** 14) * -1) + 1

v = vJoy[0]
v.x, v.y, v.z, v.rx, v.ry, v.rz, v.slider, v.dial = (int32_min,) * 8

# =============================================================================================
# Axis inversion settings (multiplier): normal = 1;  inverted = -1
# =============================================================================================
global throttle_inversion, braking_inversion, clutch_inversion
throttle_inversion = 1
braking_inversion = 1
clutch_inversion = 1

# =============================================================================================
# Mouse settings
# =============================================================================================
global mouse_sensitivity, sensitivity_center_reduction
mouse_sensitivity = 4.0

sensitivity_center_reduction = 1.0

# =============================================================================================
# Ignition cut settings
# =============================================================================================
global ignition_cut_time, ignition_cut_elapsed_time
ignition_cut_enabled = True
ignition_cut_time = 100
ignition_cut_elapsed_time = 0

global ignition_cut, ignition_cut_released
# Init values, do not change
ignition_cut = False
ignition_cut_released = True

# =============================================================================================
# Steering settings
# =============================================================================================
global steering, steering_max, steering_min, steering_center_reduction
# Init values, do not change
steering = 0.0
steering_max = float(int32_max)
steering_min = float(int32_min)
steering_center_reduction = 1.0

# =============================================================================================
# Throttle settings
# =============================================================================================
global throttle_blip_enabled
throttle_blip_enabled = False

# In milliseconds
throttle_increase_time = 300
throttle_increase_time_after_ignition_cut = 0
throttle_increase_time_blip = 50
throttle_decrease_time = 300

global throttle, throttle_max, throttle_min
# Init values, do not change
throttle_max = int32_max * throttle_inversion
throttle_min = int32_min * throttle_inversion
throttle = throttle_min

global throttle_increase_rate, throttle_decrease_rate
# Set throttle behaviour with the increase and decrease time,
# the actual increase and decrease rates are calculated automatically
throttle_increase_rate = calculate_rate(throttle_max, throttle_increase_time)
throttle_increase_rate_after_ignition_cut = calculate_rate(throttle_max, throttle_increase_time_after_ignition_cut)
throttle_increase_rate_blip = calculate_rate(throttle_max, throttle_increase_time_blip)
throttle_decrease_rate = calculate_rate(throttle_max, throttle_decrease_time) * -1
# =============================================================================================
# Braking settings
# =============================================================================================
# In milliseconds
braking_increase_time = 160
braking_decrease_time = 130

global braking, braking_max, braking_min
# Init values, do not change
braking_max = int32_max * braking_inversion
braking_min = int32_min * braking_inversion
braking = braking_min

global braking_increase_rate, braking_decrease_rate
# Set braking behaviour with the increase and decrease time,
# the actual increase and decrease rates are calculated automatically
braking_increase_rate = calculate_rate(braking_max, braking_increase_time)
braking_decrease_rate = calculate_rate(braking_max, braking_decrease_time) * -1

# =============================================================================================
# Clutch settings
# =============================================================================================
# In milliseconds
clutch_increase_time = 0
clutch_decrease_time = 50

global clutch, clutch_max, clutch_min
# Init values, do not change
clutch_max = int32_max * clutch_inversion
clutch_min = int32_min * clutch_inversion
clutch = clutch_min

global clutch_increase_rate,  clutch_decrease_rate
# Set clutch behaviour with the increase and decrease time,
# the actual increase and decrease rates are calculated automatically
clutch_increase_rate = calculate_rate(clutch_max, clutch_increase_time)
clutch_decrease_rate = calculate_rate(clutch_max, clutch_decrease_time) * -1

# assign button

# =================================================================================================
# LOOP START
# =================================================================================================

# =================================================================================================
# Activate
# =================================================================================================
if keyboard.getPressed(Key.End):
activate = not activate

if activate == True:
vJoy[0].setButton(0,int(keyboard.getKeyDown(Key.S)))
vJoy[0].setButton(1,int(keyboard.getKeyDown(Key.D)))
vJoy[0].setButton(2,int(keyboard.getKeyDown(Key.C)))
vJoy[0].setButton(3,int(mouse.wheelUp))
vJoy[0].setButton(4,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(5,int(keyboard.getKeyDown(Key.G)))
vJoy[0].setButton(6,int(keyboard.getKeyDown(Key.H)))
vJoy[0].setButton(7,int(mouse.wheelDown))
else:
vJoy[0].setButton(0,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(1,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(2,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(3,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(4,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(5,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(6,int(keyboard.getKeyDown(Key.Home)))
vJoy[0].setButton(7,int(keyboard.getKeyDown(Key.Home)))

# =================================================================================================

# =================================================================================================
# Steering logic
# =================================================================================================
if steering > 0:
steering_center_reduction = sensitivity_center_reduction ** (1 - (steering / steering_max))
elif steering < 0:
steering_center_reduction = sensitivity_center_reduction ** (1 - (steering / steering_min))

steering = steering + ((float(mouse.deltaX) * mouse_sensitivity) / steering_center_reduction)

if steering > steering_max:
steering = steering_max
elif steering < steering_min:
steering = steering_min

v.x = int(round(steering))

# =================================================================================================
# Clutch logic
# =================================================================================================
if keyboard.getPressed(Key.C):
throttle = -16383
if keyboard.getKeyDown(Key.C):
clutch = clutch + clutch_increase_rate
else:
clutch = clutch + clutch_decrease_rate

if clutch > clutch_max * clutch_inversion:
clutch = clutch_max * clutch_inversion
elif clutch < clutch_min * clutch_inversion:
clutch = clutch_min * clutch_inversion

v.z = clutch
# =================================================================================================
# Smooth Throttle
# =================================================================================================
if keyboard.getKeyDown(Key.Z):
blip = 1
elif keyboard.getKeyUp(Key.Z):
blip = 200
# =================================================================================================
# Brake y Full Brake
# =================================================================================================
if keyboard.getKeyDown(Key.X):
maxBrake = 16383
elif keyboard.getKeyUp(Key.X):
maxBrake = 2048
elif keyboard.getKeyDown(Key.J):
maxBrake = 1
# =================================================================================================
# Throttle logic
# =================================================================================================
if mouse.leftButton:
throttle = throttle + throttle_increase_rate * blip
else:
throttle = throttle + throttle_decrease_rate * blip

if throttle > throttle_max * throttle_inversion:
throttle = throttle_max * throttle_inversion
elif throttle <  throttle_min * throttle_inversion:
throttle = throttle_min * throttle_inversion

v.y = throttle

# =================================================================================================
# Braking logic
# =================================================================================================
if mouse.rightButton:
braking = braking + (braking_increase_rate*6)
else:
if braking > 4096:
braking = braking + (braking_decrease_rate * 4)
else:
braking = braking + (braking_decrease_rate * 4)

if braking > maxBrake:
braking = maxBrake
elif braking < braking_min * braking_inversion:
braking = braking_min * braking_inversion

v.rz = braking

# =================================================================================================
# Buttons post-throttle logic
# =================================================================================================
#set_button(look_left_button, look_left_key)
#set_button(look_right_button, look_right_key)
#set_button(look_back_button, look_back_key)
#set_button(change_view_button, change_view_key)
#set_button(indicator_left_button, indicator_left_key)
#set_button(indicator_right_button, indicator_right_key)

# =================================================================================================
# PIE diagnostics logic
# =================================================================================================
diagnostics.watch(v.x)
diagnostics.watch(v.y)
diagnostics.watch(v.rz)
diagnostics.watch(maxBrake)
diagnostics.watch(blip)
diagnostics.watch(activate)
чтобы протестировать код, просто скопируйте его в файл .py и запустите его с помощью freePIE, у него также есть очень полезный инструмент просмотра
Я пробовал использовать и модифицировать уже найденный скрипт для эмуляции колеса в Assetto Corsa через freePIE, с самого начала и даже до того, как я его модифицировал, он начал сильно лагать, как будто без надобности буферизует много входных данных.


Подробнее здесь: https://stackoverflow.com/questions/746 ... hon-script
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»