How to interpret clock()?

mad

In my C++ program, I measure CPU time by the clock() command. As the code is executed on a cluster of different computers (running all the same OS, but having different hardware configuration, i.e. different CPUs), I am wonderung about measuring actual execution time. Here is my scenario:

As far as I read, clock() gives the amount of CPU clock ticks that passed since a fixed date. I measure the relative duration by calling clock() a second time and building the difference.

Now what defines the internal clock() in C++? If I have CPU A with 1.0 GHz and CPU B with 2.0 GHz and run the same code on them, how many clocks will CPU A and B take to finish? Does the clock() correspond to "work done"? Or is it really a "time"?

Edit: As the CLOCKS_PER_SEC is not set, I cannot use it for convertion of clocks to runtime in seconds. As the manual says, CLOCKS_PER_SEC depends on the hardware/architecture. That means there is a dependency of the clocks on the hardware. So, I really need to know what clock() gives me, without any additional calculation.

James Kanze

The clock() function should return the closest possible representation of the CPU time used, regardless of the clock spead of the CPU. Where the clock speed of the CPU might intervene (but not necessarily) is in the granularity; more often, however, the clock's granularity depends on some external time source. (In the distant past, it was often based on the power line frequence, with a granularity of 1/50 or 1/60 of a second, depending on where you were.)

To get the time in seconds, you divide by CLOCKS_PER_SEC. Be aware, however, that both clock() and CLOCKS_PER_SEC are integral values, so the division is integral. You might want to convert one to double before doing the division. In the past, CLOCKS_PER_SEC also corresponded to the granularity, but modern systems seem to just choose some large value (Posix requires 1000000, regardless of the granularity); this means that successive return values from clock() will "jump".

Finally, it's probably worth noting that in VC++, clock() is broken, and returns wall clock time, rather than CPU time. (This is probably historically conditionned; in the early days, wall clock time was all that was available, and the people at Microsoft probably think that there is code which depends on it.)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related