0

I have a question on measuring CPU time on Ubuntu 12.04.

I want to use the CPU time as a stopping criteria in some loop. What is the best way?

while(....)
{
    //main part
    // get CPUTIME
    if(CPUTIME>= Given_Time)
    {
        break;         
    }

}

1) I can use clock(), if I don't care too much about the resolution of time.

time_t begin=clock();
....
time_t end=clock();

CPUTIME=(double)(end-begin)/(double)(CLOCKS_PER_SEC);

However, time_t many be overflow, since the running time may be long(more than an hour). How can I fix this problem?

2) The second option is using getrusage(int who, struct rusage *usage) Does it cost too much to call this function in the loop?

3) The third option is to use int clock_gettime(clockid_t clk_id, struct timespect *tp) So far, this is the best choice in my option.

Any suggestions and comments will be helpful.

Mysticial
  • 464,885
  • 45
  • 335
  • 332

1 Answers1

1

Depending on how fast your loop is running, you might not want to call the checking function every cycle. Perhaps add a loop counter and check the CPU time only if, for example, (i % 1000) == 0.

To answer your question: I'd personally use clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) because librt, the library in which this function resides, was made specifically for tasks like this. However, there's no reason that you can't use the other two; you can easily detect the overflow with clock() by detecting when the value wraps and having a separate counter that counts the number of times it wraps.

gvl
  • 903
  • 7
  • 16