Mendes
Mendes

Reputation: 18561

How to compare two elapsed times?

Consider the following code that will show me always the slowest execution time of some code:

std::chrono::steady_clock::time_point begin, end
std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;

begin = std::chrono::steady_clock::now();

... some processing to be measured ...

end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count();

if (elapsed > lastElapsed)
{
    std::cout << "The slowest execution interval is now at  " << elapsed << "us" << std::endl;
    lastElapsed = elapsed;
}

I can't compile:

/home/user/dev/MyThread.cpp:104:59: error: expected ‘;’ before ‘lastElapsed’
     std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;
                                                           ^
/home/user/dev/MyThread.cpp:104:70: error: statement cannot resolve address of overloaded function
     std::chrono::duration_cast<std::chrono::microseconds> lastElapsed;
                                                                      ^
/home/user/dev/MyThread.cpp:114:19: error: ‘lastElapsed’ was not declared in this scope
     if (elapsed > lastElapsed)

How can I fix this interval comparer and set the lastElapsed variable type accordingly?

Upvotes: 0

Views: 156

Answers (2)

ObliteratedJillo
ObliteratedJillo

Reputation: 5166

Check this:

    std::chrono::steady_clock::time_point begin, end;
    std::chrono::microseconds lastElapsed;

    begin = std::chrono::steady_clock::now();

    //... some processing to be measured ...

    end = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);

    if (elapsed > lastElapsed)
    {
        std::cout << "The slowest execution interval is now at  " << elapsed.count() << "us" << std::endl;          
    }

    lastElapsed = elapsed; 

Upvotes: 0

zdan
zdan

Reputation: 29470

Firstly, std::chrono::duration_cast is not a type, its function that returns a duration, so your declaration of lastElapsed is invalid. You can fix it like this:

auto lastElapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);

which essentially initializes lastElapsed with a value of 0.

Then when you compute elapsed use the same type:

auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - begin);

don't bother with the count() member function, until you need to output the value:

    std::cout << "The slowest execution interval is now at  " << elapsed.count() << " us" << std::endl;

Upvotes: 2

Related Questions