Reputation: 75
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:
Results obtained:
What I find uncertain is, why do the program prints to console until execution is finished and not every second as expected?
Cheers,
Upvotes: 1
Views: 2159
Reputation: 20191
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
:
cout << e<<std::flush;
std::endl
will also flush the stream in addition to adding a newline (writing \n
might 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.
Upvotes: 1