Skip to main content

Writing a Sleep that is microsecond aware?

5 replies [Last post]
Joined: 2007-11-14

We have need for a Sleep method that can sleep for less than a millisecond. The simplest approach would be to call nanotime() in a loop until the desired time has passed. While this will pressure the CPU, it isn't for very long, and any yielding seems likely to result in sleeping too long.


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2008-05-05

There is a method on Thread that offers a nanosecond parameter:

public static void sleep(long millis, int nanos)

will that work for you?

- Dave

Joined: 2004-06-19

Unlikely considering the source code for the nano second version of Thread.sleep converts it back to miliseconds and calls the less accurate method. It's mostly a pointless method.

Joined: 2005-11-01

It worth noting that on windows and linux a plain Thread.yield() or sleep(0) can wait between 40 and 100 micro-seconds. You could try a real-time operating system, but most OSes don't support short context switches.
Instead you can have a busy loop to "pause" for any amount of time. This is usually accurate to sub-micro-second (unless a context switch happens)

Joined: 2007-07-25

Use the sleep method with nanoseconds:,%20int)

However you should verify what clock accuracy you actually get, it is not going to be 1 nanosecond, of course. The accuracy will depend on your machine and OS. On my machine I am getting about 5 microseconds.

Joined: 2004-06-19

As both sleeping and yielding nearly always hand-off to native operating system code and will trigger a context switch to other threads waiting for CPU time, then sub milisecond precision can't really be achieved since most OSes won't offer it - especially not the big Seattle based one! Like you said you want to sleep for tiny amounts of time, so I don't see anything wrong with a busy-wait based approach here.