2

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

Grizzly
  • 19,595
  • 4
  • 60
  • 78
user1417815
  • 445
  • 3
  • 7
  • 16

7 Answers7

12

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;
}
Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55
  • Try changing time_t to clock_t. By the way, "nothing" means "it doesn't even compile" ? Or it is not working as expected ? – Viktor Latypov May 29 '12 at 23:00
  • its just not printing anything – user1417815 May 29 '12 at 23:03
  • I changed the types to 'clock_t'. That's the best I can do without turning on my Mac. – Viktor Latypov May 29 '12 at 23:07
  • It still not working with me, i really dont know why.. weird... it run the code with 0 problem, but dont print anything – user1417815 May 29 '12 at 23:21
  • Check out my changes. Does the 'time_counter' change ? What is the 'Gran' ? (comment out the printf(time_counter) to see the Gran). I bet it is the problem with insufficient precision of integer calculations or just some silly negation error. – Viktor Latypov May 29 '12 at 23:23
  • Yes the time_counter works and keep counting, but not the count – user1417815 May 29 '12 at 23:26
  • And another variant, with unistd.h - I use usleep() available on linux/OSX. Good luck with that, I just have to sleep myself :) – Viktor Latypov May 29 '12 at 23:28
  • thanks my brother, btw didn't know you where from russia too. Big love brother! - I have a code, as http post request using socket. The code works fine without any problem, but it eat alot of cpu power ( memory ), i posted it here.. but all people didn't want help me out.. fix it.. sp i deleted it. Can i post it, then you can take a look brother? ... i think you deserve another aceepted help. Please if you don't mind.. i'm pulling all my hair strands.. and cant fix it.. for whole month :) – user1417815 May 30 '12 at 03:37
  • Sockets, select()... Come on, form the Question here (I mean create the question, not the comment) and we'll see what can be done. – Viktor Latypov May 30 '12 at 08:29
  • Thanks for a non-`sleep()` solution. A comment: Wouldn't it be better to reset `time_counter` to 0 instead of doing `time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC)`? I get the feeling that this could solve the possible wrong accumulation of time. – rocarvaj Sep 27 '19 at 17:01
4

On Windows, you can use Sleep from windows.h:

#include <iostream>
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
    int count = 0;
    while(true)
    {
        count +=1;
        std::cout << count  << std::endl;
        Sleep(10000);
    }
}
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
2

Use sleep() : http://www.gnu.org/software/libc/manual/html_node/Sleeping.html

int count = 0;
while(true)
{
    count++;

    cout << count << endl; // print every 10 second 
    sleep(10);

}
d_inevitable
  • 4,381
  • 2
  • 29
  • 48
stan
  • 4,885
  • 5
  • 49
  • 72
2

Here is yet another example using Windows Waitable Timer. Short quote from MSDN page:

A waitable timer object is a synchronization object whose state is set to signaled when the specified due time arrives. There are two types of waitable timers that can be created: manual-reset and synchronization. A timer of either type can also be a periodic timer.

Example:

#include <Windows.h>
#include <iostream>

void main(int argc, char** argv)
{
    HANDLE hTimer = NULL;
    LARGE_INTEGER liTimeout;

    // Set timeout to 10 seconds
    liTimeout.QuadPart = -100000000LL;

    // Creating a Waitable Timer
    hTimer = CreateWaitableTimer(NULL, 
                                 TRUE,              // Manual-reset
                                 "Ten-Sec Timer"    // Timer's name
                                );
    if (NULL == hTimer)
    {
        std::cout << "CreateWaitableTimer failed: " << GetLastError() << std::endl;
        return;
    }

    // Initial setting a timer
    if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
    {
        std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
        return;
    }

    std::cout << "Starting 10 seconds loop" << std::endl;

    INT16 count = 0;
    while (count < SHRT_MAX)
    {
        // Wait for a timer
        if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)
        {
            std::cout << "WaitForSingleObject failed: " << GetLastError() << std::endl;
            return;
        }
        else 
        {
            // Here your code goes
            std::cout << count++ << std::endl;
        }

        // Set a timer again
        if (!SetWaitableTimer(hTimer, &liTimeout, 0, NULL, NULL, 0))
        {
            std::cout << "SetWaitableTimer failed: " << GetLastError() << std::endl;
            return;
        }
    }
}

Also, you can use a Waitable Timer with an Asynchronous Procedure Call. See this example on MSDN.

Sergei Danielian
  • 4,938
  • 4
  • 36
  • 58
1

As others have said, you want a sleep() function. Cross-platform issues can come up though. I found this thread about that issue, which you may want to look at.

Community
  • 1
  • 1
SirPentor
  • 1,994
  • 14
  • 24
0

In C++11 (or 14) and later you also got the chrono library with the standard lib so you can just call that, which is great for multithreading too:

#include <chrono>

for (;;)
{
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  if (someEndCondition)
    break;
}
Bostrot
  • 5,767
  • 3
  • 37
  • 47
0
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
     while (true)
     {     
         std::this_thread::sleep_for(std::chrono::seconds(10));
          std::cout << i << std::endl;
     } 
}
ToDo
  • 1