Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sleep in Nanoseconds

 
Larry Frissell
Ranch Hand
Posts: 82
2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20388
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maneesh Godbole
Saloon Keeper
Posts: 10971
11
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There will also be an overhead for context switching.
 
Larry Frissell
Ranch Hand
Posts: 82
2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic