File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Sleep in Nanoseconds Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sleep in Nanoseconds" Watch "Sleep in Nanoseconds" New topic

Sleep in Nanoseconds

Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
I want to perform a simple math function with a very small elapse time between each calculation. I am trying to use TimeUnit with Nanosecond sleep, but the elapse time for 10 iterations is almost 50 millisecond. If I remove the sleep the loop runs in less than 1 millisecond. I would appreciate any suggestions.

elapse time for this test was 47.0
[ August 25, 2008: Message edited by: Larry Frissell ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20275

According to the API,
Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Now in Windows, sleep actions can easily take 10ms, even though you only want to sleep 1. Therefore, you should never rely on sleep actions for timing issues.

How To Ask Questions How To Answer Questions
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10825

There will also be an overhead for context switching.

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
Okay, thank you for the response. I was reading this API under TimeUnit:

public void sleep(long timeout)
throws InterruptedExceptionPerforms a Thread.sleep using this unit. This is a convenience method that converts time arguments into the form required by the Thread.sleep method.

I guess I misunderstood the API.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46375
Originally posted by Rob Prime:
According to the API,

Now in Windows, sleep actions can easily take 10ms . . .
And somebody on the Ranch had a bug in Windows whereby Thread.sleep(i) where i%10!=0 can alter the system clock. I don't know whether this is still the case, but there are more details here.
I agree. Here's the link:
subject: Sleep in Nanoseconds
It's not a secret anymore!