Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do something n times per second?

Suppose you had to perform a task with a requirement of doing it fixed number of times (say 20,000) per second.

How would you time the event?

like image 818
James Raitsev Avatar asked Oct 03 '13 20:10

James Raitsev


2 Answers

For 20K times per second you need to busy wait for the next interval. I suggest wait until the next time it should have run to iron out the impact of jitter.

long start = System.nanoTime();
long rate = 20000;
for(long i = 0; ; i++) {

   // do something

   long end = start + i * 1000000000L / rate;
   while(System.nanoTime() < end);
}

The reason you can't use built in Scheduler is that the minimum time slice is 100 micro-seconds which is 10K times per second and the minimum sleep time on many platforms is 1 milli-second.

like image 93
Peter Lawrey Avatar answered Oct 28 '22 03:10

Peter Lawrey


If you're implementing a control system which requires fixed-interval execution and you want to implement it in Java, read up on real-time Java.

If you just need something executed repeatedly and millisecond-granularity is sufficient, look at Timer or ScheduledThreadPoolExecutor.

If you need finer granularity (i.e., more than 1000 times per second) but you don't strictly require your code to execute at precise intervals, you may be able to get by with Peter Lawrey's busy-wait solution.

like image 32
rob Avatar answered Oct 28 '22 02:10

rob