Why does clock_gettime return different values depending on how the function is timed?

85 Views Asked by At

I'm trying to time a fast section of C code with clock_gettime. I'm roughly doing this

struct timespec start, end1, end2;

clock_gettime(CLOCK_MONOTONIC_RAW, &start);
function_a();
clock_gettime(CLOCK_MONOTONIC_RAW, &end1);
function_b();
clock_gettime(CLOCK_MONOTONIC_RAW, &end2);

result1 = timespec_diff(&start, &end1);
result2 = timespec_diff(&start, &end2);

result1 is around 130ns. result2 is around 630ns. If I comment out function_a, result1 goes to around 30ns, which is roughly the time taken by two consecutive clock_gettime calls. But result2 only goes down to about 600ns.

function_a is a few control statements and pointer dereferences. Nothing crazy.
This is on an AMD EPYC CPU. I've run hundreds of warm up loops and averaged over millions of loops to get the numbers.

How could this happen? Why does result1 have an extra 100ns?

0

There are 0 best solutions below