Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use clock() to count program execution time

I'm using something like this to count how long does it takes my program from start to finish:

int main(){
    clock_t startClock = clock();
    .... // many codes
    clock_t endClock = clock();
    printf("%ld", (endClock - startClock) / CLOCKS_PER_SEC);
}

And my question is, since there are multiple process running at the same time, say if for x amount of time my process is in idle, durning that time will clock tick within my program?

So basically my concern is, say there's 1000 clock cycle passed by, but my process only uses 500 of them, will I get 500 or 1000 from (endClock - startClock)?

Thanks.

like image 281
Derek Li Avatar asked Sep 19 '11 21:09

Derek Li


3 Answers

This depends on the OS. On Windows, clock() measures wall-time. On Linux/Posix, it measures the combined CPU time of all the threads.

If you want wall-time on Linux, you should use gettimeofday().

If you want CPU-time on Windows, you should use GetProcessTimes().

EDIT:

So if you're on Windows, clock() will measure idle time.

On Linux, clock() will not measure idle time.

like image 136
Mysticial Avatar answered Nov 11 '22 23:11

Mysticial


clock on POSIX measures cpu time, but it usually has extremely poor resolution. Instead, modern programs should use clock_gettime with the CLOCK_PROCESS_CPUTIME_ID clock-id. This will give up to nanosecond-resolution results, and usually it's really just about that good.

like image 24
R.. GitHub STOP HELPING ICE Avatar answered Nov 12 '22 01:11

R.. GitHub STOP HELPING ICE


As per the definition on the man page (in Linux),

The clock() function returns an approximation of processor time used by the program.

it will try to be as accurate a possible, but as you say, some time (process switching, for example) is difficult to account to a process, so the numbers will be as accurate as possible, but not perfect.

like image 1
Diego Sevilla Avatar answered Nov 11 '22 23:11

Diego Sevilla