| Author |
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. Output run: elapse time for this test was 47.0 [ August 25, 2008: Message edited by: Larry Frissell ]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Maneesh Godbole
Saloon Keeper
Joined: Jul 26, 2007
Posts: 8439
|
|
|
There will also be an overhead for context switching.
|
[Donate a pint, save a life!] [How to ask questions] [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:
sleep 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
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
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.
|
 |
 |
|
|
subject: Sleep in Nanoseconds
|
|
|