每10秒循环一次

use*_*815 3 c++

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

喜欢:

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

打印:

1
2
3
4
5
ect...
Run Code Online (Sandbox Code Playgroud)

我不知道怎么样,请帮帮我们

Vik*_*pov 9

我的尝试.(几乎)完美的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;
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以对每次迭代进行控制,这与基于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;
}
Run Code Online (Sandbox Code Playgroud)