Coder
Coder

Reputation: 3120

CPU time measurement

I have following code snippet and i am trying to evaluate the time take by CPU

However I am getting some weird results

struct timeval begin, end;
double cpu_time=0.0;
gettimeofday(&begin, NULL);
long cpu_sum = 0;


for (i = 0; i < size; i++) {
 cpu_sum += array[i] * array[i];
}    
 gettimeofday(&end, NULL);
 cpu_time = end.tv_sec - begin.tv_sec * 1000;
 cpu_time += (end.tv_usec - begin.tv_usec) / 1000;

 printf("calculated sum: %d using CPU in %lf ms \n", cpu_sum, cpu_time);

Sample result = 1296217442.000000 ms

I dont think this is correct time value in ms. Can anyone help whats wrong here?

Any help would be appreciated.

Thanks

Upvotes: 1

Views: 4221

Answers (4)

Mazheng
Mazheng

Reputation: 166

Pentium class cpu has an instruction to read the current time-stamp counter variable ,which is a 64-bit variable, into registers (edx:eax).If you want get real CPU time,you can use this instruction.You can get CPU tick. Details... this link,please. rdtsc

Upvotes: 1

ugoren
ugoren

Reputation: 16441

A small addition to Alnitak's answer:

You define cpu_time as double, I assume it's in order to handle possible overflows (run time greater than ~2M seconds). But in the line:

cpu_time = (end.tv_sec - begin.tv_sec) * 1000;

The right-hand side is evaluated as an unsigned integer, and will overflow after about 4M seconds. Assigning it to a double afterwards won't help.
So if you really care about long run times, do this:

cpu_time = (double)(end.tv_sec - begin.tv_sec) * 1000;

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

You need to fix your operator precedence:

cpu_time = (end.tv_sec - begin.tv_sec) * 1000;
cpu_time += (end.tv_usec - begin.tv_usec) / 1000;

In the original you're multiplying begin.tv_sec by 1000, and then subtracting that from end.tv_sec;

Also, not that gettimeofday() measures "wall clock time", not strictly CPU time, where the latter is the better measure of how much "CPU effort" the process took. If another process uses the CPU at the same time as yours then the results will not be accurate.

For "proper" CPU time you should use the (POSIX standard) getrusage() system call.

Upvotes: 13

Damon
Damon

Reputation: 70106

If you want CPU time, you probably want to use clock_gettime instead with the CLOCK_PROCESS_CPUTIME_ID parameter.

That's the probably most convenient (and accurate) way to get both real time and cpu time using the same function, only changing one parameter.

Upvotes: 1

Related Questions