Home > OS >  Using two time values in while loop. The while loop doesn't stop when condition no longer 1. C
Using two time values in while loop. The while loop doesn't stop when condition no longer 1. C

Time:02-06

My while loop isn't stopping even though one of the values becomes 'greater than' and the condition changes from 1 to 0.

Before the while loops starts I set the time now in milliseconds. milliseconds_now
I also set a time five seconds in the future. milliseconds_then

I have (milliseconds_now < milliseconds_then) in the while loop. It should only be 1 for five seconds. I also print out (milliseconds_now < milliseconds_then) within the loop and it goes from printing '1' to printing '0' after five seconds.

I expect the loop to stop after five seconds. Instead it continues.

This is what I have in the terminal when I run the program at five seconds. It just keeps looping.

1644097691885 1644097692070
1
1644097691935 1644097692070
1
1644097691986 1644097692070
1
1644097692036 1644097692070
1
1644097692086 1644097692070
0
1644097692136 1644097692070
0
1644097692186 1644097692070
0
1644097692236 1644097692070
0
1644097692287 1644097692070
0
1644097692337 1644097692070
0
1644097692387 1644097692070
0
1644097692437 1644097692070

The code.

#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace std::chrono;

auto now = high_resolution_clock::now();
auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

auto milliseconds_then = milliseconds_now   5000;
    
int main() {
    while (milliseconds_now < milliseconds_then) {

        auto now = high_resolution_clock::now();
        auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

        cout << milliseconds_now << " " << milliseconds_then << "\n";
        cout << (milliseconds_now < milliseconds_then) << "\n";

        usleep(50000);
    };
};

CodePudding user response:

the milliseconds_now inside the loop is not the same milliseconds_now being tested in the while loop. Change it to

while (milliseconds_now < milliseconds_then) {

    auto now = high_resolution_clock::now();
    milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

    cout << milliseconds_now << " " << milliseconds_then << "\n";
    cout << (milliseconds_now < milliseconds_then) << "\n";

    usleep(50000);
};

why? you are declaring a new variable inside the loop, often the compiler will warn you about it.

  •  Tags:  
  • Related