본문 바로가기

CS Fundamental

[CS Fundamental] 디지털 시계 프로그램을 만들어야 한다. 초단위로 표시해야 한다. 어떻게 작성할 것인가? 그렇게 작성 하면 장점과 단점은 무엇인가?

 

 

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.

 

 

12

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.