Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop every 10 second

Tags:

c++

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

like image 475
user1417815 Avatar asked Nov 17 '25 20:11

user1417815


1 Answers

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.

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\n", count++);
    }
    return 0;
}
like image 141
Viktor Latypov Avatar answered Nov 19 '25 10:11

Viktor Latypov