Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance:

for i in range(10000000):
    print(i)
    sleep(.334)

Watch the numbers it prints. If it's anything like my computer, it's not even remotely regular. Is this function supposed to be accurate? Have I found a bug somewhere in my system?

If this function is not supposed to be accurate, what function would be more accurate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're just looking at the output, buffering might make it appear slightly jittery. You could try to explicitly flush the output, but then you're also at the mercy of whatever is displaying the output. I might even hazard a guess that you're using Jupyter Notebook in your browser, which will also have a bunch of buffering/latency as it updates.

Another issue is that if you expect to be running every 1/3 of a second, is that you will suffer from accumulated errors. It will take a little time to run the loop, print a value (printing will take orders of magnitude more time than the other parts), then start to sleep again. A way to bypass this would be that after you finish doing whatever you want to do (I assume something more interesting than count), compute the time until the next 1/3rd of a second and sleep for that amount of time. Something like:

import random
import time

sleep_until = time.monotonic() + 1/3

for n in range(100):
    print(time.monotonic() % 100, n)
    time.sleep(random.random() / 4) # some "work"

    now = time.monotonic()
    if sleep_until > now:
        time.sleep(sleep_until - now)
    else:
        pass
        #print('task took too long')
    sleep_until += 1/3

For me it gives something like:

48.34696656104643 0
48.68041984003503 1
49.08346292399801 2
49.41925806296058 3
49.72542790300213 4
50.07280854298733 5
50.41882419097237 6
50.74827564903535 7
51.08352101803757 8
51.41813271504361 9
51.75208444998134 10
52.08399672002997 11
52.41870043799281 12

So it bounces around a bit (I'm also running this in Jupyter, which may contribute), but won't stack up error as it runs.

The real question though is what are you trying to do?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...