我寫了一個腳本來從儀器中讀取數據並將數據寫入CSV文件。每次採樣之間的時間間隔可以由用戶設置。一秒採樣率很常見。我使用了time.sleep,並嘗試使用timeElapsed = timeEnd - timeBegin提取腳本的處理時間。問題是這不夠好。時間在流逝,所以不時有劇本跳過一秒鐘。在我的電腦上,它大約每2-3分鐘發生一次。所以我的問題是如何提高時間的準確性。每秒運行while循環
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)
而不是睡覺,檢查當前時間是否大於或等於一段時間;這樣,錯誤不能累積。 –
我認爲這是你想要的:http://stackoverflow.com/a/13151104/3881403 –