使用 clock() 输出持续时间,但输出相乘

Output a duration with clock() but output is multiplied

所以,我想以秒为单位显示程序打开的持续时间, 但它显示乘秒而不是一个字符。前任。 1 到 11111 这是代码:

int main() {
   clock_t start;
   double duration;
   int seconds;

   start = clock();
   while (true) {
      if ((clock() - start) % CLOCKS_PER_SEC == 0) {
        cout << (clock() - start) / (double)CLOCKS_PER_SEC;
      }
   }
}

输出:

01111111111111111111111222222222233333333333334444444445555555556666666666666667777777777777

帮我解决这个问题

您的 if 检查完全错误。想象一下,如果您的 while 循环运行两次并且 clock() 没有变化,因为它循环得非常快。它要么输出两次,要么都不输出。这不可能是对的。

正确的检查是查看自上次生成输出后是否至少过了一秒。

 clock_t last_output;
 start = last_output = clock();
 while (true) {
      if (clock() > (last_output + CLOCKS_PER_SEC)){
          last_output += CLOCKS_PER_SEC;
          cout << (clock() - start) / (double)CLOCKS_PER_SEC;
    }
 }

完整代码如下:

#include <time.h>
#include <iostream>

int main()
{
    clock_t start, last_output;

    start = last_output = clock();
    while (true)
    {
        if (clock() > (last_output + CLOCKS_PER_SEC))
        {
            last_output += CLOCKS_PER_SEC;
            std::cout << (clock() - start) / (double)CLOCKS_PER_SEC << std::endl;
        }
     }
}