我编写了一个脚本来读取仪器并将数据写入CSV文件。每次采样之间的时间间隔可以由用户设置。一秒采样率非常普遍。我使用了time.sleep并尝试使用timeElapsed = timeEnd - timeBegin来提取脚本的处理时间。问题是这还不够好。时间在流逝,所以剧本不时跳过一秒钟。在我的电脑上大约每2-3分钟发生一次。所以我的问题是我如何才能提高计时的准确性。
import csv
import datetime
import time
import os.path
no_of_meas = 200
cur_meas = 1
time_interval= 1 #time between each sample given in seconds, 1 second is the lowest recommended value
with open('test.csv', 'a', newline='') as fp:
while cur_meas <= no_of_meas:
timeBegin = time.time()
cur_time = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S.%f')
a = csv.writer(fp, delimiter='\t')
data = [[cur_time, cur_meas]]
a.writerows(data)
fp.flush() #flush and os.fsync to be sure that data is written to disk
os.fsync(fp.fileno())
print(', '.join(map(str, data)))
cur_meas += 1
timeEnd = time.time()
timeElapsed = timeEnd - timeBegin
time.sleep(time_inter-timeElapsed)
答案 0 :(得分:0)
您不应该在每次通话时重置基准时间,因为您正在创建稍微关闭的新时间刻度。您必须从全球时间基础进行计算。并且您需要使用浮点数以确保Python不进行任何整数舍入。
只是相关部分:
interval = 1.0
start_time = time.time()
with open('test.csv', 'a', newline='') as fp:
while cur_meas <= no_of_meas:
next_in = (start_time + (cur_meas - 1.0) * interval) - time.time()
if next_in > 0.0:
time.sleep(next_in)
# your measuring code.
这样,代码将计算当前测量的预期时间并在此之前休眠或在已经达到时间后立即继续。
答案 1 :(得分:0)
您需要将延迟基于实际时间而不是每次迭代延迟。以下是处理它的一种可能的替代方法,它不会长时间漂移,但会使用更多的CPU。
import time
def tick(time_interval):
next_tick = time.time() + time_interval
while True:
time.sleep(0.2) # Minimum delay to allow for catch up
while time.time() < next_tick:
time.sleep(0.2)
yield True
next_tick += time_interval
time_interval = 1.0
ticker = tick(time_interval)
while cur_meas <= no_of_meas:
# Do measurement code
next(ticker)
单个迭代将是下一个0.2秒(或者你需要的很好)。如果迭代延迟(例如CPU加载),这将允许“赶上”#39;每隔0.2秒,直到时间再次同步。