0

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Ema
  • 79
  • 1
  • 6
  • On what operating system? `gettimeofday` suggests some POSIX one, perhaps Linux... – Basile Starynkevitch Feb 22 '18 at 09:05
  • 1
    Not really. Put the code in a loop, calculate the total for each call inside the loop, and then show the average. And note that 50 iterations is usually to little, try doing it at least a few thousand times. And with optimizations enabled. – Some programmer dude Feb 22 '18 at 09:06
  • Operating system is Linux. – Ema Feb 22 '18 at 09:06
  • @Ema: then you need to edit your question to improve it, at least by tagging it better – Basile Starynkevitch Feb 22 '18 at 09:08
  • @Ema You are measuring too small units of work. Your operating system has a lot of things to do, (flush written data to disk, handle network packets, handle timekeeping, handle memory allocation etc.) and there are a lot of processes running that does various taks.. Fluctuations like you see in the handful of miliseconds range is perfectly normal. So what you need to do is to time your computation perhaps 1000 times. (e.g. by running the the computation in a loop of 1000, or run your entire program 1000 times, and divide by 1000 to get an average. – nos Feb 22 '18 at 09:31

1 Answers1

2

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547