Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing chrono::duration with an integer

Tags:

c++

c++-chrono

I am trying to compare the time elapsed to execute a piece of code with a fixed integer.

For example:

auto startProcessingTime = chrono::high_resolution_clock::now();
chrono::duration<int> timeDiff = (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startProcessingTime));

    if (timeDiff > 12) {
        // DO SOMETHING
        continue;
    }

However on running this I get the following error:

Invalid operands to binary expression ('chrono::duration' and 'int')

How can I convert timeDiff to an integer?

I have also tried:

chrono::seconds s = chrono::duration_cast<chrono::seconds>(timeDiff);

However,

Invalid operands to binary expression ('chrono::seconds' (aka 'duration') and 'int')

Any help would be greatly appreciated.

like image 777
rrz0 Avatar asked Aug 31 '25 03:08

rrz0


1 Answers

You need to tell it what 12 means. Is it seconds? Milliseconds? So either cast it:

chrono::seconds(12)

Or (my favorite) make it a chrono literal. If you mean 12 seconds, then:

using namespace std::chrono_literals;
// ...

if (timeDiff > 12s) {

If it's milliseconds:

if (timeDiff > 12ms) {
like image 74
Nikos C. Avatar answered Sep 02 '25 17:09

Nikos C.