File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sleep in Nanoseconds" Watch "Sleep in Nanoseconds" New topic
Author

Sleep in Nanoseconds

Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
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: 19718
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10451
    
    8

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
    
    2
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: 39393
    
  28
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: http://aspose.com/file-tools
 
subject: Sleep in Nanoseconds