Chinna
Chinna

Reputation: 4002

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?

Upvotes: 1

Views: 158

Answers (2)

user1110743
user1110743

Reputation: 64

It is fine only if you want to burn 100% CPU. Otherwise, you should add a library call that lets your loop spend some or most of its time sleeping, for example, nanosleep, and tune your delay to the granularity that suits your application.

Upvotes: 0

Japu
Japu

Reputation: 40

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.

Upvotes: 2

Related Questions