How accurate is python's time.sleep()? - Stack Overflow
How accurate is python's 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?
stackoverflow.com
The accuracy of the time.sleep function depends on your underlying OS's sleep accuracy. For non-real-time OSs 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).
Non-real-time Linux kernels have minimum sleep intervals much closer to 1ms than 10ms, but it varies in a non-deterministic manner.
The time.sleep method has been heavily refactored in the upcoming release of Python (3.11). Now similar accuracy can be expected on both Windows and Unix platform, and the highest accuracy is always used by default. Here is the relevant part of the new documentation:
On Windows, if secs is zero, the thread relinquishes the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution. On Windows 8.1 and newer the implementation uses a high-resolution timer which provides resolution of 100 nanoseconds. If secs is zero, Sleep(0) is used.
Unix implementation:
- Use clock_nanosleep() if available (resolution: 1 nanosecond);
- Or use nanosleep() if available (resolution: 1 nanosecond);
- Or use select() (resolution: 1 microsecond).
So just calling time.sleep will be fine on most platforms starting from python 3.11, which is a great news ! It would be nice to do a cross-platform benchmark of this new implementation similar to the @wilbert 's one.
'CS Fundamental' 카테고리의 다른 글
[CS Fundamental] 웹 성능 진단하기 (0) | 2025.01.16 |
---|---|
[CS Fundamental] 파이썬 Yield 키워드 (0) | 2025.01.16 |
[CS Fundamental] IMAP이란? (0) | 2025.01.16 |
[CS Fundamental] 셸 (0) | 2025.01.14 |
[CS Fundamental] 인텔 x86 구조 및 ARM의 발전 과정 (0) | 2025.01.14 |