如何使计时器更有效率

时间:2018-07-02 06:37:13

标签: python python-3.x performance raspberry-pi raspberry-pi3

我对编码还很陌生,我想知道如何提高编码效率。我在树莓派上运行它,它将执行其他任务,因此我希望它尽可能容易运行。该代码将使用一个磁传感器来记录由安装在车轮上的磁铁进行的通过,并由此确定车轮外径的速度。实现一些采用最后五个速度输出并给出某种平均值的东西会很有用,但前提是它不会对代码的复杂性造成太大影响。真的非常有帮助!

from gpiozero import Button
import time
global t0
t0 = time.clock()
raduis = 300
button = Button (21)
from signal import pause

def calculate_speed(radius):
    global t0
    t1 = time.clock
    interval = t1 - t0
    speed = radius/interval
    print (speed, 'mm/sek')

y = True
while y == True:
    button.when_pressed = calculate_speed(radius)
    time.sleep(0.2)
    #used to prevent one pass of the magnet from recording many passes

2 个答案:

答案 0 :(得分:3)

您应该将五个最后的速度输出存储在一个数组(列表)中,然后可以计算平均速度

speed_records = []
def calculate_speed(radius):
    global t0
    t1 = time.clock
    interval = t1 - t0
    speed = radius/interval
    print (speed, 'mm/sek')
    speed_records.append(speed) # Adds one speed record to the list
    if len(speed_records) >= 5: # checks if there are 5 five records available
        last_five_records = speed_records[-5:] # Seperates five last records
        average = sum(last_five_records) / 5
        print('Average Speed:',average) # Prints out the average
    if len(speed_records) > 10: # Free Up some memory
        speed_records = list(set(speed_records) - set(speed_records[:5])) #removes the first five records 

答案 1 :(得分:2)

以下代码使用模块化算法来遍历单个列表,添加和覆盖值,并打印平均速度。调整iterations,以控制平均传球次数。

from gpiozero import Button
from signal import pause
import time

radius = 300
button = Button (21)

iterations = 5
speeds = [0] * iterations
speed_idx = 0

def calculate_speed(radius):
    global speeds, speed_idx
    t1 = time.time()
    speeds[speed_idx] = radius / (t1- t0)
    print (sum(speeds) / iterations, 'mm/sek')
    speed_idx += 1
    speed_idx %= iterations

t0 = time.time()
while True:
    button.when_pressed = calculate_speed(radius)
    time.sleep(0.2)
    t0 = time.time()

请注意,从某种意义上讲,这需要进行5次测量才能“加速”。如果需要的话,可以添加一个if语句,以避免打印出前4条记录。

另外,如果您想更平滑地测量速度,我想到您可以使用一个值来保存最近N次通过的速度总和,并且每次减去平均值(假设有N个总和) ,然后添加新速度。可能需要多走几步才能稳定下来,但是此后应该可以使报告的速度稍有降低。

相关问题