Why is this output waiting for something after it?
Question
void Wait(double Duration)
{
clock_t End;
End = clock() + (Duration*CLOCKS_PER_SEC);
while (clock() < End)
{
// This loop just stalls the program.
}
}
My function works perfectly half the time, but it occasionally stalls the program before it's even called. For example, take the following snippet:
cout << "This is\n";
Wait(2.5)
cout << "a test!";
You'd expect the first line to appear immediately and the second line to appear after 2.5 seconds, but it sometimes ALL appears after 2.5 seconds. What's the deal?
Solution
try
cout.flush();
before your Wait
OTHER TIPS
That might be because of I/O buffering.
You should flush the output buffer (either try << endl
instead of '\n'
or writing cout.flush
) manually.
Try cout << "This is" << endl;
It looks like a buffering, not clock issue.
The flush()/std::endl has already been mentioned - but is your intention to really consume 100% of one core while you wait? This is what the while()
loop is doing! If you want a nicer approach to "waiting", consider one of the following:
- boost::thread::sleep() - millisecond granularity
- alarms (1 second granularity)
- select()
- pthread_cond_timedwait()
etc.