I'll take your money.
First, a change because the optimizer will pre-compute the sum:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
long a, bound=10000000;
long sum = 0;
if (argc > 1) {
bound = atoi(argv[1]);
}
/* for loop execution */
for( a = 0; a < bound; a++ ) {
sum += a;
}
printf("sum: %lu\n", sum);
return 0;
}
I'll time the performance across a range of values.
% cc tmp.c && time ./a.out 1000000
sum: 499999500000
0.005u 0.000s 0:00.00 0.0% 0+0k 0+0io 1pf+0w
% cc tmp.c && time ./a.out 10000000
sum: 49999995000000
0.030u 0.000s 0:00.03 100.0% 0+0k 0+0io 1pf+0w
% cc tmp.c && time ./a.out 100000000
sum: 4999999950000000
0.303u 0.000s 0:00.33 90.9% 0+0k 0+0io 1pf+0w
You'll notice that my timings for 10000000, at 0.03 seconds, was comparable to the timings in the essay.
If the printf overhead were the dominate cost then we would expect to see less variance in the timing. Instead, we see there's a linear increase, which is exactly what we expect if the loop is the primary cost.
So no, most of the time is not spent in printing the result.
I'll also test with optimizations enabled:
% cc -O3 tmp.c && time ./a.out 1000000
sum: 499999500000
0.000u 0.000s 0:00.00 0.0% 0+0k 0+0io 1pf+0w
% cc -O3 tmp.c && time ./a.out 10000000
sum: 49999995000000
0.000u 0.001s 0:00.00 0.0% 0+0k 0+0io 1pf+0w
% cc -O3 tmp.c && time ./a.out 100000000
sum: 4999999950000000
0.000u 0.000s 0:00.00 0.0% 0+0k 0+0io 1pf+0w
% cc -O3 tmp.c && time ./a.out 1000000000
sum: 499999999500000000
0.000u 0.000s 0:00.00 0.0% 0+0k 0+0io 1pf+0w
The optimizer does pretty well on this code.
First, a change because the optimizer will pre-compute the sum:
I'll time the performance across a range of values. You'll notice that my timings for 10000000, at 0.03 seconds, was comparable to the timings in the essay.If the printf overhead were the dominate cost then we would expect to see less variance in the timing. Instead, we see there's a linear increase, which is exactly what we expect if the loop is the primary cost.
So no, most of the time is not spent in printing the result.
I'll also test with optimizations enabled:
The optimizer does pretty well on this code.