time.time() not working to run while loop for predetermined time in Cython

痞子三分冷 提交于 2020-01-30 04:59:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/55997211/time-time-not-working-to-run-while-loop-for-predetermined-time-in-cython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!