问题描述
我有一个Python模块,其中包含一个while循环,该循环应该运行固定的时间.我通过在time.time()的输出中添加一个常量并运行直到time.time()大于该变量来完成此操作.这没有出现任何问题,但是在Cython中,同样的事情对我不起作用.现在我越来越不准时机了.
I had a Python module which included a while loop which was supposed to run for a fixed amount of time. I did this by adding a constant to the output of time.time() and running until time.time() was greater than that variable. This did not present any issues, but the same thing is not working for me in Cython. Now I'm getting wildly off timings.
仅举一个最小的例子来说明这一点:
Just for a minimal example demonstrating this:
import time
cdef float wait_time = 3
def slow():
cdef float end_time = time.time() + wait_time
while time.time() < end_time:
pass
print("Done")
%timeit -r1 -n1 slow()
Done
44.2 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
19.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
35.5 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
20.6 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
20 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
56 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
1min 3s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
32.9 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%timeit -r1 -n1 slow()
Done
1min 5s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
趋向于遵循的一般行为是,基本上没有等待,除了在运行该功能之前暂停了一段时间之后,在这种情况下,等待过多.
The general behavior this tends to follow is that there will be essentially no wait, except for after pausing for a while before running the function, in which case there is an excessive wait.
推荐答案
Python的 float
是C的 double
.C的 float
通常只有 24个有效位(一个(含隐式),精确度为128秒(自2004年起).当您的加法从四舍五入变为四舍五入时,它从过去的一分钟变为将来的一分钟.
Python’s float
is C’s double
. C’s float
usually has only 24 significand bits (one of them implicit), giving it a precision of 128 seconds (since 2004). When your addition changes from rounding down to rounding up, it moves from one minute in the past to a value one minute in the future.
这篇关于time.time()无法在Cython中运行while循环达预定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!