Question

I am working on a project which has no determined algorithm to solve using C language. I am Using Monte Carlo technique for solving that problem. And the number of random guesses I want to limit to the execution time specified by the user. This means I want to make full use of the execution time limit defined by the user (as a command line argument) to make as many random iterations as possible. Can I check the execution time elapsed so far for a loop condition?

for(trials=0;execution_time<specified_time;trials++)

If so, how do I do it? Or if there is any other way also, it is welcomed. Thank You.

P.S. I am using Code Blocks 10.05 for coding and GNU compiler.

Was it helpful?

Solution

Yes, if you have a sufficiently fine-grained clock on your computer (and you do).

  1. Record the time when the simulation started.

  2. For each trip around the loop, find the current time and the corresponding delta between the start time and now. If the value is bigger than the limit, stop.

If you use time() with its one-second granularity, beware of the quantization effects. If the user said '1 second', you could end up running for a tiny fraction of a second if your program started at T=N.999s and you stopped at T=(N+1).001s. The same effect is possible with any quantum, but since microseconds and nanoseconds are the normal sub-second granularities, the size of the quantum ceases to be a problem.

The high-resolution clock functions I know of are:

  • clock_gettime() - POSIX (nanosecond)
  • gettimeofday() - POSIX (microsecond)
  • times() - Unix System V(CLK_TCK per second)
  • ftime() - Ancient Unix (millisecond)
  • clock() - ISO C - (CLOCKS_PER_SEC)
  • time() - ISO C - (second)

OTHER TIPS

You can try standard function clock() which returns number of internal clock ticks since program start. See documentation of that function for more information.

Thank you everybody for your comments. A simple two line code did the job for me:

time_t start_time = time(NULL);
while (((int)(time(NULL) - start_time)) < execution_time)
{
   /* ...... */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top