Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...