2016-08-01 8 views
2

一定の時間間隔で何度かタスクを繰り返したいのですが、私はそれを一様なやりかたで行いたいので、1秒間に4回タスクを実行したい場合はt = 0,0.25,0.5および0.75で実行される。今私がやっているので、アクションをx秒間に一度だけ実行する

import math 
import socket 

s = socket.socket(...) #not important 

time_step = 1./num_times_executed 
for _ in num_times_executed: 
    now = time.time() 
    s.sendto(...) #action i do 
    time.sleep(max(0,time_step-(time.time()-now))) 

は、しかし、多くのオーバーヘッドがあり、大きなループは私が得るより多くのドリフトです。たとえばnum_times_executed = 800の場合、1.1秒かかるので〜10%間違っています...

精度が良い方法がありますか?

答えて

2
time_step = 1./num_times_executed 
start = time.time() 
for i in num_times_executed: 
    s.sendto(...) #action i do 
    next_send_time = start + (i+1) * time_step 
    time.sleep(max(0,next_send_time - time.time())) 

時間ステップが開始時間から確実に設定されているので、ここではドリフトを取得しません。以前は、now = time.time()を設定する前に起こった小さな計算は小さなドリフトを引き起こしましたが、今はtime_stepがs.sendto(...)コマンドを実行するのに十分長い限り、ドリフトを起こすべきではありません。

関連する問題