0
void Wait(double Duration)
{
    clock_t End;
    End = clock() + (Duration*CLOCKS_PER_SEC);

    while (clock() < End)
    {
        // This loop just stalls the program.
    }
}

我的函数有一半的时间可以完美运行,但它偶尔会在程序被调用之前停止。例如,采用以下代码段:

cout << "This is\n";
Wait(2.5)
cout << "a test!";

您希望第一行立即出现,第二行在 2.5 秒后出现,但有时 ALL 会在 2.5 秒后出现。这是怎么回事?

4

4 回答 4

4

尝试

cout.flush();

在你等待之前

于 2010-11-09T18:51:09.593 回答
4

这可能是因为 I/O 缓冲。您应该手动刷新输出缓冲区(尝试<< endl而不是'\n'写入)。cout.flush

于 2010-11-09T18:51:47.733 回答
2

尝试cout << "This is" << endl;

它看起来像一个缓冲,而不是时钟问题。

于 2010-11-09T18:50:45.517 回答
2

已经提到了 flush()/std::endl - 但是您是否打算在等待时真正消耗 100% 的一个内核?这就是while()循环正在做的事情!如果您想要一种更好的“等待”方法,请考虑以下方法之一:

  1. boost::thread::sleep() - 毫秒粒度
  2. 警报(1 秒粒度)
  3. 选择()
  4. pthread_cond_timedwait()

等等

于 2010-11-09T19:06:41.367 回答