Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

Chris Angelico rosuav at gmail.com
Wed Jun 18 06:34:21 EDT 2014


On Wed, Jun 18, 2014 at 7:52 PM, crow <wentlv at gmail.com> wrote:
> So, my question: under what kind of condition, time.sleep would suspend longer time than expected?
>
> Anybody got interested?

There are several reasons the sleep time is always described as "at
least" that long. Firstly, your process will always sleep for some
multiple of the kernel's internal task switching resolution. That
doesn't explain why time.sleep(1) will sleep for nine seconds, but if
you try this, you'll see that at work:

>>> for i in range(1000): time.sleep(0.001)

In theory, that should be the same as time.sleep(1), right? Well, no.
On my systems it sleeps for 2-3 seconds at least, which suggests that
there's a minimum of 2-3 milliseconds of sleep time. And it could
easily sleep for a lot longer than that.

The second thing to note is that every PC you're ever likely to run
your code on [1] is a multitasking system. If some higher-priority
process [2] is running when your sleep expires, you won't preempt it,
so you'll sleep for longer. Or if your code or crucial data has been
paged out to disk, you have to wait to see it paged back in before you
can count that your sleep has finished. (This is especially noticeable
if you do something immediately after sleeping that you hadn't done
for a long time, so it'll tend to get paged out.)

Finally, it's entirely possible for some other process to explicitly
stop yours, at least on Unix systems. (I don't know if it's possible
on Windows.) If that happens, you won't wake up until you get
correspondingly continued. But chances are this isn't happening to
you, unless you're pressing Ctrl-Z to background a process or
something.

I've not often seen sleep(1) become nine seconds without a VERY good
reason, so there ought to be something that you can dig into. But just
remember that you can't use this for actual timing, and you're fine.
That is, don't do this:

t = time.time()
while True:
    t += 1
    time.sleep(1)

Because that's majorly flawed (for several reasons). If you let that
run for ten seconds, it'll probably be within 1-2 seconds; but if you
let that run all day, it could easily be out by a goodly number of
minutes.

ChrisA

[1] If you're running on a single-process real-time system, you *know*
the game rules are different, so you know to ignore what I'm saying
here. For 99%+ of python-list users, this will be true.
[2] Technically, if as many such processes are running as your
computer has CPU concurrency, eg one per core. Unless you have
execution affinities set. And other complexities. Look, I know this is
oversimplifying, okay! :)



More information about the Python-list mailing list