James Raitsev
James Raitsev

Reputation: 96461

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?

Upvotes: 7

Views: 2586

Answers (4)

Andrey Chaschev
Andrey Chaschev

Reputation: 16516

Sounds like a perfect job for the RateLimiter from Guava.

EDIT

Had a glance into RateLimiter's implemention - well, not an ideal candidate for a such a high rate, because to increment counter it uses synch-blocks and sleeps. But it should be fine if it is possible to change the granularity, i.e. split your 20.000 into 100 packs of 200 items each.

Upvotes: 1

rob
rob

Reputation: 6247

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.

Upvotes: 1

Ján Srniček
Ján Srniček

Reputation: 525

It depends of what are you doing in that task,for example if you are doing some networking ,where you are trying to do some connection it will depends on connection timeout and some other factors. If you are doing some basic operations you will be able to control the upper limit of operations ,for example maximum of 20 operations per second ,but you will never be able to control the lower limit because of other task that are running in pc.So it really depends on what are you doing,on whitch hardware you are running(specially procesor) and how bussy is that computer.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533660

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.

Upvotes: 10

Related Questions