I’m trying to implement a “timer” function in C++ for the program to do something after some seconds.
However, I’ve got unexpected results.
short e, sum;
clock_t start;
double duration=0;
for (e=0; e<4; e++) {
start = clock();
while (duration < 1) {
duration = (clock() - start)/(double)CLOCKS_PER_SEC;
}
cout << duration;
duration = 0;
sum += e;
/* Calculate EPOCH error */
cout << e;
}
cout << "\n" << e<< "\n";
The results I expect are:
- console output every second, followed by e (0,1,2,3)
- at the end of the execution I expect sum to be 0+1+2+3 = 6,
Results obtained:
- console output followed by e, all together when execution finishes
- sum = 6
What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,
Your problem is that the output stream isn’t flushed during your loop. Actually writing pieces of text to the console is somewhat expensive. Therefore the input is buffered and only written to the console when a flush occurs. Flushing the stream can be accomplished by streaming
std::flush:std::endlwill also flush the stream in addition to adding a newline (writing\nmight also do it, but that’s not guaranteed).As a sidenote: you might want to consider adding some sort of seperators between your numbers to make the output readable.