偶尔执行操作

时间:2019-04-22 15:25:07

标签: python python-2.7 datetime time sampling

我目前正在尝试(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

1 个答案:

答案 0 :(得分:0)

这样的作品行吗?

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。