我目前正在尝试(Python 2.7)设置一个以固定采样频率(即每x毫秒)执行的动作。但是,我面临的结果不准确。使用代码波纹管(采样频率为1000Hz,代码运行5秒),我希望有5 * 10000个样本。相反,我的价值越来越低。我想最好有5000Hz的采样频率,但我也很满意1000Hz。
谁能帮我?
import datetime
count = 0
loop_start_time = start_time = datetime.datetime.now()
while datetime.datetime.now() - loop_start_time <= datetime.timedelta(0,5,0): #loop for 5 seconds
if datetime.datetime.now() - start_time >= datetime.timedelta(0,0,1000): #perform an action every 1000 microseconds (1 millisecond, 0.1 seconds)
start_time = datetime.datetime.now()
count = count + 1
print count
最好的问候,T2
会这样的吗?
import time
import threading
total_time = 5
increment_time = .1
is_running = False
count = 0
def incrementCounter():
global count
global is_running
is_running = True
threading.Timer(increment_time, incrementCounter).start()
count += 1
# Any additional code should be put here
end_time = time.time() + total_time
while time.time() < end_time:
if not is_running:
incrementCounter()
print count
输出为此我得到~50。