1

I want to measure the execution time of peace of code.
I'm doing it with clock() function.
Here the example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void) {
    clock_t begin=0, end=0;

    begin = clock();
    printf("hello world!!\n");
    end = clock();

    printf("Begin %E\n",begin);
    printf("End %E\n",end);
    printf("Clocks %E\n",end-begin);
    printf("Clocks per second %E\n", CLOCKS_PER_SEC);
    printf("Time %E\n", (end-begin)/CLOCKS_PER_SEC);

    return 0;
}

Here the output:

hello world!!
Begin 2.529616E-320
End 2.535545E-320
Clocks 5.928788E-323
Clocks per second 4.940656E-318
Time 0.000000E+00

Time is 0!
What I'm doing wrong? Is the output correct?

Thanks a lot

jww
  • 97,681
  • 90
  • 411
  • 885
Michael Vaysman
  • 277
  • 3
  • 16
  • It's less than picoseconds. I think it is impossible in windows... – Michael Vaysman Mar 02 '16 at 09:03
  • 1
    measuring execution time of single printf statement is pointless. – pranav Mar 02 '16 at 09:07
  • 1
    Possible duplicate of [What’s the correct way to use printf to print a clock\_t?](http://stackoverflow.com/questions/1083142/what-s-the-correct-way-to-use-printf-to-print-a-clock-t) – Ruud Helderman Mar 02 '16 at 09:11
  • Test the approach by measuring the time it takes to calculate `for(int i = 1; i < 5; i++) sqrt(i);` and check that. One of the reasons why execution time is almost 0 is because "Hello world" is a hardcoded literal, and it doesn't take that long to fetch it from the file's `.text` section. – Shark Mar 02 '16 at 09:15
  • You may be experiencing the [Microsoft Minute](http://www.userfriendly.org/cartoons/archives/99mar/19990318.html). – jww Apr 30 '18 at 00:53

1 Answers1

6

%E needs floating point (float or double). You are sending integer values

To divide ensure number is floating

(end-begin+0.0)/CLOCKS_PER_SEC);

mksteve
  • 12,614
  • 3
  • 28
  • 50