Nabil
Nabil

Reputation: 327

How to make interval of a second in executing a loop(C++)

Actually, i am trying to make a stopwatch. Here i have made a loop to increase the value of an integer named seconds every time the loop executes. but it executes too fast. So, i want the loop to execute after every second. i've read some discussion on clock and time but i couldn't even understand that clearly. So, i wasn't able to use that in my code. [This haven't been long since i've started learning C++. So, I still don't understand advanced 'thing'.]

Here is the code:

     int main()
{

int looper=2;
int second=00;
while (looper=2){
    second++;
    cout<<second<<endl;}

Upvotes: 1

Views: 1223

Answers (3)

Andreas DM
Andreas DM

Reputation: 10998

You can use sleep_for or sleep_until (C++11) to accomplish your task (in <thread>).
And including <chrono> for time.

int main()
{
    using namespace std::this_thread;
    using namespace std::chrono;

    vector<int> v { 1,2,3,4,5 };

    for (const auto& i : v) {
        cout << i << '\n';
        sleep_for(seconds(1));
        // or sleep_until(system_clock::now() + seconds(1));
    }
}

And in C++14 with chrono literals:

sleep_for(1s);

Upvotes: 2

Stephen
Stephen

Reputation: 1518

This function relies on <ctime> to work:

#include <ctime>

//function that waits the specified number of seconds
void wait(double seconds) {
    clock_t start = clock();

    while (double((clock() - start) / CLOCKS_PER_SEC) < seconds) {
        //keep looping until number of seconds have passed
    }

}

Upvotes: 0

TarmoPikaro
TarmoPikaro

Reputation: 5223

For example:

#include <stdio.h>
#include <windows.h>

void main()
{
    int iFullDelay = 1000;

    DWORD start = GetTickCount();
    #define TIMES_TO_POLL_PER_SECOND 20

    for (int i = 0; i < TIMES_TO_POLL_PER_SECOND; i++)
    {
        Sleep(iFullDelay / TIMES_TO_POLL_PER_SECOND);
        printf("%d ", i);
    }
    DWORD end = GetTickCount();

    printf("\r\n%d ms elapsed\r\n", end-start);
}

This will print out:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1016 ms elapsed

So actually within 1 second we execute 20 times some operation - in this case printf. printf itself takes some time, so that's why 1016 ms is elapsed, not exactly 1000 ms = 1 s. So if you're executing something in a loop - you need to ensure it will not consume too much time, or somehow measure elapsed time.

Upvotes: -1

Related Questions