Francesco
Francesco

Reputation: 650

C++ Compare High Resolution Clock with fixed number

I'm working on an emulator and I don't understand how to compare elapsed time measured with the chrono library with the fixed number like (CPUCycles * 0.0000005).

Something like

auto lastTime = std::chrono::steady_clock::now();
while (condition)
{
    if ((std::chrono::steady_clock::now() - lastTime) >= (CPUCycles * 0.0000005))
    {
        //do something;
    }
    else
    {
        //do something else;
    }
}

that at the moment give me the error

Error C2676 binary '>=': 'std::chrono::duration<__int64,std::nano>' does not define this operator or a conversion to a type acceptable to the predefined operator

Upvotes: 0

Views: 680

Answers (2)

Flamefire
Flamefire

Reputation: 5807

std::chrono::steady_clock::now() - lastTime returns a duration hence you need to compare it to a duration. What this means depends on what your compared-to value means. The best/correct way is to convert that to a duration.

So your CPUCycles * 500 returns the duration in nanoseconds? (0.0000005 == 500e-9) Then tell the compiler that:

if ((std::chrono::steady_clock::now() - lastTime) >= CPUCycles * std::chrono::nanoseconds(500))

See how clean this conveys the meaning? There is 1 cycle per 500ns -> So your time passed is CPUCycles times that.

The alternative is getting the count of a duration with the member function count() but you'll mostly want to cast the duration first:

auto diff = std::chrono::steady_clock::now() - lastTime;
if(std::chrono::duration_cast<std::chrono::nanoseconds>(diff).count() >= CPUCycles * 500) ...

But this looses all the clarity the chrono gives you.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

The difference between two time_point object is a duration, which aren't readily convertible from any number. You have to explicitly construct a proper duration object.

There are a few standardized duration aliases, like std::chrono::nanoseconds which you can use as std::chrono::nanoseconds(500):

if ((std::chrono::steady_clock::now() - lastTime) >= (CPUCycles * std::chrono::nanoseconds(500)))

Or if you use the std::literals::chrono_literals namespace you can use the "user" define literal ns:

if ((std::chrono::steady_clock::now() - lastTime) >= (CPUCycles * 500ns))

Upvotes: 2

Related Questions