clinuxloopstiminguserspace

Best way to run a loop for certain amount of time


I have to run a loop for certain amount of time. I know the following way to do that.

get start time;
while(1)
{
   getcurrenttime;
   if(start time + time to run >= current time)
      break;
   else 
      do what ever you want.
}

Is it ok ? or any other better way to do this?


Solution

  • I suggest you introduce any "Thread.Sleep" inside the loop to prevent the use and energy comsuption of the processor, improving the performance of other processes and operating system. If you want to wait a fix time you can use the system threading sleep directly otherwise if you want to wait an undefined time you could have a loop with exit conditions like maximum time or another conditional expressions but you must adjusts the waiting time with small sleep values.