When does Thread.sleep (1000) sleep for less than 1000 milliseconds?

In this interesting article about deceit, programmers believe on time , one of them

Thread.sleep (1000) sleeps for> = 1000 milliseconds.

When is it not?

+6
source share
2 answers

According to this (Introducing hibernation by the Windows operating system, which will be caused by the Thread.sleep thread): If dwMilliseconds is less than the resolution of the system clock, the thread may sleep less than the specified period of time. If dwMilliseconds is more than one tick, but less than two, the wait can be somewhere between one and two ticks and so on. To increase the accuracy of the wait interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and timeBeginPeriod to set the minimum timer resolution.

+4
source

The OS only responds to interruptions and therefore handles sleep expiration during an interruption. Correctly, the interrupt rate can be increased with timeBeginPeriod . The difficulty is that for the expiration of the Sleep() function, two conditions must be met:

  • An interruption should occur.
  • DwMilliseconds is about to expire.

Condition 2 is the problem here. DwMilliseconds will compare with elapsed system time during interruptions. The system time will cause the Sleep() function to expire in increments in file format, in other words, when n times the increase in system time becomes greater than dwMilliseconds. Thus, you will not be able to get 1 ms sleep delay. It depends on the hard and software systems and configuration (increment / granularity of the system time).

A closer look with some examples can be found here.

To answer the question: Thread.sleep (1000) sleeps for> = 1000 milliseconds, always TRUE! Edit: when executed immediately after Thread.sleep (1)

Edit: however, Thread.sleep (1) sleeps for> = 1 milliseconds may not always be TRUE

+4
source

Source: https://habr.com/ru/post/919940/


All Articles