我们可以使用gevent.sleep()来获得精确的计时吗?

时间:2015-06-01 22:12:27

标签: python real-time embedded-linux gevent

我们是否可以在我们的应用程序中的任何位置使用gevent.sleep()或在任何第三方库上使用gevent.monkey.patch_time()而不会出现问题,尤其是会出现精确的计时?

例如,某些库使用time.sleep()函数来测量用于控制嵌入式(点阵式LCD等)设备的几微秒。我们可以安全地修补这些库而没有问题吗?

1 个答案:

答案 0 :(得分:0)

没有。 gevent.sleep()不适合精确的时间安排。

这是测试代码:

import gevent
import time


for i in range(10):
        test_duration = 0.1 ** i
        start_time = time.time()
        gevent.sleep(test_duration)
        end_time = time.time()

        gevent_duration = end_time - start_time

        err = (gevent_duration - test_duration) / test_duration
        print("test_duration: %.10f secs, err: %%%.10f" % (test_duration, err))

结果如下:

ceremcem@cca-erik:gevent-timing-test$ python test.py 
test_duration: 1.0000000000 secs, err: %0.0009050369
test_duration: 0.1000000000 secs, err: %0.0037088394
test_duration: 0.0100000000 secs, err: %0.0192871094
test_duration: 0.0010000000 secs, err: %0.1119842529
test_duration: 0.0001000000 secs, err: %9.9791755676
test_duration: 0.0000100000 secs, err: %108.9109649658
test_duration: 0.0000010000 secs, err: %1095.0102081299
test_duration: 0.0000001000 secs, err: %10878.0397644043
test_duration: 0.0000000100 secs, err: %108407.9279174804
test_duration: 0.0000000010 secs, err: %1087902.9764404292
ceremcem@cca-erik:gevent-timing-test$ python test.py 
test_duration: 1.0000000000 secs, err: %0.0009670258
test_duration: 0.1000000000 secs, err: %0.0031008720
test_duration: 0.0100000000 secs, err: %0.0271072388
test_duration: 0.0010000000 secs, err: %0.1529922485
test_duration: 0.0001000000 secs, err: %10.1293792725
test_duration: 0.0000100000 secs, err: %117.3032989502
test_duration: 0.0000010000 secs, err: %1191.0928955078
test_duration: 0.0000001000 secs, err: %11898.4712829590
test_duration: 0.0000000100 secs, err: %119089.0802612304
test_duration: 0.0000000010 secs, err: %1188992.4539794917

如您所见,错误也不可预测

这就是为什么在这种情况下应该谨慎使用gevent.monkey.patch_all()的原因。