Skip to content
Advertisement

Computation time of processor varies on execution, each time by using gettimeofday() in a C program

I am trying to compare the computation time for performance comparison using different C libraries with gettimeofday() by including time.h and sys/time.h header files.

I used gettimeofday() at the start and end of my computation and took the difference. But each time I execute my C code, I get fluctuating time as answer. For example

0.007 sec,
0.004 sec,
0.009 sec etc. 

Is there a way I could take the average of 50 such results other than manually make 50 such executions and taking the average of all results.

Advertisement

Answer

But each time I execute my C code, I get fluctuating time as answer.

This fluctuation is unrelated to C or to gettimeofday. Current processors and operating systems make such execution time fluctuate (e.g. because cache misses or branch prediction may be non-deterministic, and because context switches, preemption, page faults, interrupts etc… happen at any time).

In practice, read carefully time(7) (maybe you also want to use clock_gettime(2) and/or clock(3) and/or time(1)…). Set-up your benchmark to last at least one second (so repeat your benchmarked functions many times). Run several benchmarks and several times the same benchmark.

Advertisement