gpt4 book ai didi

c++ - 每 10 秒循环一次

转载 作者:太空狗 更新时间:2023-10-29 19:39:39 24 4
gpt4 key购买 nike

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

喜欢:

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

打印:

1
2
3
4
5
ect...

我不知道怎么办,请大家帮帮我

最佳答案

我的尝试。 (几乎)完美的 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;
}

关于c++ - 每 10 秒循环一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10807681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com