Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How accurate is python's time.sleep()?

Tags:

python

time

sleep

I can give it floating point numbers, such as

time.sleep(0.5) 

but how accurate is it? If i give it

time.sleep(0.05) 

will it really sleep about 50 ms?

like image 256
Claudiu Avatar asked Jul 15 '09 20:07

Claudiu


People also ask

How does time sleep work in python?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

Is time sleep blocking python?

sleep() , your code will need to wait for the Python sleep() call to finish before the thread can exit. The reason you'd want to use wait() here is because wait() is non-blocking, whereas time. sleep() is blocking. What this means is that when you use time.

What is the time of sleeping time of python?

Sleeping time of python is three times six, which is equal to 18 hours. Awake time of python is the unshaded portion, which contains one quarter of the circle.

How do you wait 0.5 seconds in python?

Python's time module contains many time-related functions, one of which is sleep() . In order to use sleep(), you need to import it. sleep() takes one argument: seconds. This is the amount of time (in seconds) that you want to delay your code.


1 Answers

The accuracy of the time.sleep function depends on your underlying OS's sleep accuracy. For non-realtime OS's like a stock Windows the smallest interval you can sleep for is about 10-13ms. I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.

Update: Like mentioned in the docs cited below, it's common to do the sleep in a loop that will make sure to go back to sleep if it wakes you up early.

I should also mention that if you are running Ubuntu you can try out a pseudo real-time kernel (with the RT_PREEMPT patch set) by installing the rt kernel package (at least in Ubuntu 10.04 LTS).

EDIT: Correction non-realtime Linux kernels have minimum sleep interval much closer to 1ms then 10ms but it varies in a non-deterministic manner.

like image 95
Joseph Lisee Avatar answered Nov 07 '22 08:11

Joseph Lisee