user3808217
user3808217

Reputation: 145

Comparison of Duration/Seconds in C++ using chrono doesnt work as supposed?

EDIT: Works just fine, I messed up in another place of my code.

I am trying to increase an Integer once every minute, using C++11 chrono library. For some reasons, the comparison does not work as it should: It just returns true every time. Is something wrong with the cast to seconds? Shouldn't the result be an int, containing the difference of both time points in seconds?

Would really appreciate your help! Here's the Code:

std::chrono::time_point<std::chrono::system_clock> starttime = std::chrono::system_clock::now();

int timeLine = 0;

int main() {
    while (true) {
        std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

        int seconds = timeLine * 60;

        if ((std::chrono::duration_cast<std::chrono::seconds>(starttime - now)).count() + seconds <= 0) {
            timeLine++;
            nextConstellation();
            cout << "Timeline: " << timeLine << endl;

        }
    }
}

Upvotes: 0

Views: 8950

Answers (1)

Howard Hinnant
Howard Hinnant

Reputation: 218750

Here is a safer, and more readable way to write this code:

std::chrono::time_point<std::chrono::system_clock> starttime = std::chrono::system_clock::now();

int timeLine = 0;

int main() {
    while (true) {
        std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();

        std::chrono::seconds seconds = timeLine * std::chrono::minutes{1};

        if (starttime - now + seconds <= std::chrono::seconds{0}) {
            timeLine++;
            nextConstellation();
            std::cout << "Timeline: " << timeLine << std::endl;

        }
    }
}

In a nutshell, stay within the chrono-type system, and trust it to do the units conversions for you, implicitly wherever possible.

Or perhaps even more simply:

    // ...
    auto timelimit = timeLine * std::chrono::minutes{1};

    if (now  - starttime >= timelimit) {
    // ...

And if in C++14, add using namespace std::chrono_literals and:

    auto timelimit = timeLine * 1min;

Upvotes: 4

Related Questions