Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute a loop n times in 1 second

Tags:

java

loops

timer

I am trying to execute couple of instructions or a function N times in one second. How can i do this in java? As follows...

//in one second
while(N)
{
  printf(".........");
  int x=0;
  printf("The value of x is ");
}

but the question actually goes little deeper.. I am trying to plot pixels manually and I want the no of rotations per second effect... so basically, it has to execute N times for a second (But this is done infinitely )

thanks in advance

like image 707
JS_VIPER Avatar asked Feb 07 '13 07:02

JS_VIPER


1 Answers

You can never be sure it will happen exactly N times per second, but it goes like this:

long taskTime = 0;
long sleepTime = 1000/N;
while (true) {
  taskTime = System.currentTimeMillis();
  //do something
  taskTime = System.currentTimeMillis()-taskTime;
  if (sleepTime-taskTime > 0 ) {
    Thread.sleep(sleepTime-taskTime);
  }
}
like image 134
Dariusz Avatar answered Sep 24 '22 23:09

Dariusz