What is the problem with this program it is supposed to calculate the elapsed time of each function call but to my surprise, the elapsed time is always ZERO because the begin
and end
are exactly the same. Does anyone have an explanation for this?
This is the output I get:
TIMING TEST: 10000000 calls to rand()
2113 6249 23817 12054 7060 9945 26819
13831 6820 14149 13035 30858 13924 26467
4268 11314 28400 5239 4496 27757 21452
10878 25064 9049 6508 29612 11373 29913
10234 31769 16167 24553 1875 23992 30606
2606 19539 2184 14832 27089 27474 23310
, .. , ,
End time: 1610034404
Begin time: 1610034404
Elapsed time: 0
Time for each call:,10f
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NCALLS 10000000
#define NCOLS 7
#define NLINES 7
int main(void) {
int i, val;
long begin, diff, end;
begin = time(NULL);
srand(time(NULL));
printf("\nTIMING TEST: %d calls to rand()\n\n", NCALLS);
for (i = 1; i <= NCALLS; ++i) {
val = rand();
if (i <= NCOLS * NLINES) {
printf("%7d", val);
if (i % NCOLS == 0)
putchar('\n');
} else
if (i == NCOLS * NLINES + 1)
printf("%7s\n\n", ", .. , ,");
}
end = time(NULL);
diff = end - begin;
printf("%s%ld\n%s%ld\n%s%ld\n%s%,10f\n\n",
"End time: ", end,
"Begin time: ", begin,
"Elapsed time: ", diff,
"Time for each call:", (double)diff / NCALLS);
return 0;
}