Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - Loop every 10 second

How to load a loop every 10 second and add +1 to the count and print it?

like:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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
", count);
            count++;
        }

        printf("DebugTime = %f
", 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.

EDIT: 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
", count++);
    }
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...