每10秒循环 [英] Loop every 10 second
本文介绍了每10秒循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何每10秒加载一个循环,并为计数加+1,并打印?
How to load a loop every 10 second and add +1 to the count and print it?
如:
int count;
while(true)
{
count +=1;
cout << count << endl; // print every 10 second
}
print:
1
2
3
4
5
ect...
我不知道怎么样,请帮助我。
i dont know how, please help me out guys
推荐答案
我的尝试。 (几乎)完美的POSIX。也可以在POSIX和MSVC / Win32上使用。
My try. (Almost) perfectly POSIX. Works on both POSIX and MSVC/Win32 also.
#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;
}
这种方式你也可以控制每次迭代, )的方法。
This way you can also have the control on each iteration, unlike the sleep()-based approach.
此解决方案(或基于高精度计时器的同样)也确保时序中没有错误累积。
This solution (or the same based on high-precision timer) also ensures that there is no error accumulation in timing.
编辑:OSX的东西,如果所有的失败
OSX stuff, if all else fails
#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;
}
这篇关于每10秒循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文