Derek Li
Derek Li

Reputation: 3111

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.

Upvotes: 6

Views: 9267

Answers (3)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

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.

Upvotes: 2

Mysticial
Mysticial

Reputation: 471229

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.

Upvotes: 11

Diego Sevilla
Diego Sevilla

Reputation: 29021

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.

Upvotes: 1

Related Questions