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?

Was it helpful?

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:

  1. boost::thread::sleep() - millisecond granularity
  2. alarms (1 second granularity)
  3. select()
  4. pthread_cond_timedwait()

etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top