每 10 秒循环一次

新手上路,请多包涵

如何每 10 秒加载一个循环并将 +1 添加到计数并打印它?

喜欢:

 int count;
    while(true)
    {
       count +=1;
       cout << count << endl; // print every 10 second
    }

打印:

 1
2
3
4
5
ect...

我不知道怎么做,请帮帮我

原文由 user1417815 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

我的尝试。 (几乎)完美的 POSIX。也适用于 POSIX 和 MSVC/Win32。

 #include <stdio.h>
#include <time.h>

const int NUM_SECONDS = 10;

int main()
{
    int count = 1;

    double time_counter = 0;

    clock_t this_time = clock();
    clock_t last_time = this_time;

    printf("Gran = %ld\n", NUM_SECONDS * CLOCKS_PER_SEC);

    while(true)
    {
        this_time = clock();

        time_counter += (double)(this_time - last_time);

        last_time = this_time;

        if(time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
        {
            time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
            printf("%d\n", count);
            count++;
        }

        printf("DebugTime = %f\n", time_counter);
    }

    return 0;
}

这样,您还可以控制每次迭代,这与基于 sleep() 的方法不同。

这种方案(或同样基于高精度定时器)也保证了计时没有误差累积。

编辑:OSX的东西,如果一切都失败了

#include <unistd.h>
#include <stdio.h>

const int NUM_SECONDS = 10;

int main()
{
    int i;
    int count = 1;
    for(;;)
    {
        // delay for 10 seconds
        for(i = 0 ; i < NUM_SECONDS ; i++) { usleep(1000 * 1000); }
        // print
        printf("%d\n", count++);
    }
    return 0;
}

原文由 Viktor Latypov 发布,翻译遵循 CC BY-SA 3.0 许可协议

#include <iostream>
#include <chrono>
#include <thread>
int main()
{
     while (true)
     {
         std::this_thread::sleep_for(std::chrono::seconds(10));
          std::cout << i << std::endl;
     }
}

原文由 ToDo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题