1

The following code was run in codeblocks, gcc compiler.

#include <sys/time.h>
#include<stdio.h>
int sumN(int n) {
int i,sum;
for(i=0; i<n; i++) {
    sum += i;
}
return sum;
}

int main() {
struct timeval stop, start;
int i;

for(i=0; i<10000;i+=100)
    {
        gettimeofday(&start, NULL);
        sumN(i);
        gettimeofday(&stop, NULL);
        printf("%d : %lu\n",i, stop.tv_usec - start.tv_usec);
    }
return 0;
}

and I get the following output. Is there an issue with the gettimeofday function? Or the output is right? I need to also plot a graph based on multiple input size for function and the time taken for the function execution. enter image description here

ead
  • 32,758
  • 6
  • 90
  • 153
this.shivi
  • 301
  • 3
  • 7

1 Answers1

2

The call of the function sumN(i)is optimized out (I guess you are not compiling with -O0), because the value returned is not used at all. You can see it in the resulting assembly:

...
call    gettimeofday
xorl    %esi, %esi
movq    %rsp, %rdi
call    gettimeofday
...

as you can see there is no call of sum(N)in between of the gettimeofday.

Use the returned value and it will not be optimized out:

...
gettimeofday(&start, NULL);
res=sumN(i);
gettimeofday(&stop, NULL);
printf("%d : %d, %lu\n",i, res, stop.tv_usec - start.tv_usec);//print the result, avoiding optimization!
...
ead
  • 32,758
  • 6
  • 90
  • 153
  • 2
    Good catch. Also, there could be rollover: start=1.999999 and end=2.000003, so `tv_sec` should be factored in. And, on modern x86 CPUs, `sumN` could execute so fast that low values of `i` in `main` might show up as zero because `sumN` executes in under 1us--the granularity of `gettimeofday` (i.e. `clock_gettime` might be a better choice as it [typically] has 1ns resolution) – Craig Estey Feb 01 '17 at 21:35