0
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?

Maxpm
  • 24,113
  • 33
  • 111
  • 170
  • 1
    There is almost certainly a better way to do what you really want to do. Let us know your platform/compiler, and we can give better advice. – John Dibling Nov 09 '10 at 18:50
  • Does this only happen for you with a cout? Keep in mind that it's buffered. So if you don't flush, I think you might get the behavior you're experiencing. – Bart Nov 09 '10 at 18:51
  • I'm not sure if this is correct, but is it possible the compiler is optimizing away the loop as it doesn't appear to do anything? See this question: http://stackoverflow.com/questions/3592557/optimizing-away-a-while1-in-c0x – AshleysBrain Nov 09 '10 at 18:57
  • 3
    Be carefull with the information you are giving away. They will first ask for the platform/compiler, then your address. Finally you may end up with a bunch of programmers in your kitchen trying help you with your beer. – vitaut Nov 09 '10 at 19:07

4 Answers4

4

try

cout.flush();

before your Wait

John Boker
  • 82,559
  • 17
  • 97
  • 130
4

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.

lx.
  • 2,317
  • 1
  • 22
  • 32
2

Try cout << "This is" << endl;

It looks like a buffering, not clock issue.

vitaut
  • 49,672
  • 25
  • 199
  • 336
2

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.

Nim
  • 33,299
  • 2
  • 62
  • 101