What's the relationship between the real CPU frequency and the clock_t in C?

648 Views Asked by At

What's the relationship between the real CPU frequency and the clock_t (the unit is clock tick) in C?

Let's say I have the below piece of C code which measures the time that CPU consumed for running a for loop.
But since the CLOCKS_PER_SEC is a constant value (basically 1000,000) in the C standard library, I wonder how the clock function does measure the real CPU cycles that are consumed by the program while it runs on different computers with different CPU frequencies (for my laptop, it is 2.6GHz).

And if they are not relevant, how does the CPU timer work in the mentioned scenario?

#include <time.h>
#include <stdio.h>
int main(void) {
  clock_t start_time = clock();    
  for(int i = 0; i < 10000; i++) {}
  clock_t end_time = clock();
  printf("%fs\n", (double)(end_time - start_time) / CLOCKS_PER_SEC); 
  return 0;
}
3

There are 3 best solutions below

1
einpoklum On

Effectively, clock_t values are unrelated to the CPU frequency.

See longer explanation here.

While clock_t-type values could have, in theory, represented actual physical CPU clock ticks - in practice, they do not: POSIX mandates that CLOCKS_PER_SEC be equal to 1,000,000 - one million. Thus the clock_t function returns a value in microseconds.

11
Yunnosch On

For providing the information used in the shown code, measuring/knowing/using the CPU cycles is not relevant.

For providing the elapsed time, it is only necessary to measure the time.
Reading a hardware timer would be one way to do so.
Most computers (even non-embedded ones) do contain timers which are especially counting ticks of a clock with known constant frequency. (They are specifically not "CPU timers".)
Such a timer can be read and yields a value which increases once per tick (of constant period). Where "known period" means a period know to some appropriate driver for that timer, simplified "known to the clock() function, not necessarily known to you".

Note that even if the number of used CPU cycles were known, calculating the elapsed time from that info is near impossible nowadays, in the presence of:

  • pipelines
  • parallelisms
  • interrupts
  • branch prediction

More things influencing/preventing the calculation, from comment contribution:

frequency-scaling, temperature throttling and power settings (David C. Rankin)

0
n. m. could be an AI On

There is no such thing as "the real CPU frequency". Not in everyone's laptop, at any rate.

On many systems, the OS can lower and raise the CPU clock speed as it sees fit. On some systems there is more than one kind of central processor or core, each with a different speed. Some CPUs are clockless (asynchronous).

Because of all this and for other reasons, most computers measure time with a separate clock device, independent from the CPU clock (if any).