High resolution sleep (Linux)

Tim Roberts timr at probo.com
Sat May 5 19:42:33 EDT 2007


John <janzon at gmail.com> wrote:
>
>The table below shows the execution time for this code snippet as
>measured by the unix command `time':
>
>for i in range(1000):
>	time.sleep(inter)
>
>inter       execution time      ideal
>0                     0.02 s            0 s
>1e-4                4.29 s            0.1 s
>1e-3                4.02 s            1 s
>2e-3                4.02 s            2 s
>5e-3                8.02 s            5 s
>
>Hence it seems like the 4 s is just overhead and that the time.sleep
>method treats values below approximately 0.001 as 0.
>
>Is there a standard way (or slick trick) to get higher resolution? If
>it is system dependent it's acceptable but not very nice :)

Consider what you're asking here.  The operating system can only age the
timer list and re-evaluate process ready states when a process goes into
kernel mode, either by releasing the CPU or hitting the end of its time
slice.  In order to know that a process has reached the end of its time
slice, it has to be interrupted by something, typically the timer
interrupt.

In order to provide 10us sleep resolution, the timer interrupt would have
to fire every 10us.  The overhead of handling the timer interrupt and
rescheduling that often is quite significant.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list