Laughing at myself

Marcus Alanen marcus at infa.abo.fi
Tue May 13 13:29:51 EDT 2003


On Tue, 13 May 2003 10:22:39 -0600, Daniel Fackrell
<unlearned at DELETETHIS.learn2think.org> wrote:
>Okay, I think I'm slightly puzzled again.  time.sleep(x) appears to behaving
>differently depending on the magnitude of x.

Look at the man pages of sleep(3), usleep(3) and nanosleep(2) on your
Linux system.

Especially in the BUGS section of nanosleep(2), the granularity of the
sleeping is in 1/HZ, which is often 0.01 seconds. Thus, when sleeping for
0.001 seconds, you are actually sleeping 0.01! Naturally, this leads
to a magnitude more of total sleep time.

<guess>
When your sleep time is low enough, the operating system (Or
Python. Or the C library) may decide to implement it as a busy wait,
and then the total sleep time will drop again. Note that the overhead
of the actual call will take some time, which is why you still don't
get around 1 second total sleep time.
</guess>

Similar reasoning applies to other operating systems, I guess.

Be warned, however: the above is certainly not an _accurate_
description of how any operating system does it, but it's an adequate
general rule. The *point* is, "don't assume that sleep() returns
immediately after the time has elapsed." If you remember this, you can
forget about my guesses above. ;)

>Redhat 7.0 (Linux 2.2.16-22):
>sleeptime: 1.0, iterations: 1, total: 0.993653059006
>sleeptime: 0.1, iterations: 10, total: 0.997701048851
>sleeptime: 0.01, iterations: 100, total: 0.998471021652
>sleeptime: 0.001, iterations: 1000, total: 9.99859297276

Here, each sleep(0.001) actually means sleep(0.01).

>sleeptime: 0.0001, iterations: 10000, total: 99.9983990192

And here the same thing happens.

>sleeptime: 1e-05, iterations: 99999, total: 1000.03835404

Again.

>sleeptime: 1e-06, iterations: 1000000, total: 92.6922489405

Perhaps the C library decided to take a shortcut???

Regards,
Marcus




More information about the Python-list mailing list