Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No match for "operator =" when using std::chrono::high_resolution_clock

When I compiled this timer.hpp header file below, the compiler said:

error: no match for ‘operator=’ (operand types are ‘std::chrono::_V2::system_clock::time_point {aka std::chrono::time_point > >}’ and ‘std::__success_type > >::type {aka std::chrono::duration >}’) end = std::chrono::high_resolution_clock::now() - start;

I guess the variable type for start and end is wrong. What is the correct type? I want to use std::chrono::high_resolution_clock.

#include <chrono>

namespace timer{
static std::chrono::system_clock::time_point start, end;

void initTime(){
    start = std::chrono::high_resolution_clock::now();
}


void endTime(){
    end = std::chrono::high_resolution_clock::now() - start;
}

}

timer.hpp is supposed to be used with some main file.
By calling timer::initTime() before some function that I want to measure and calling timer::endTime() after the function, I would get the timing result (the getter for the duration time is omitted here).

like image 555
mallea Avatar asked Feb 04 '23 05:02

mallea


1 Answers

There are two problems with this code:

static std::chrono::system_clock::time_point start, end;
/* ... */

void endTime(){
    end = std::chrono::high_resolution_clock::now() - start;
}

You declare end as a time point, but then on the right-hand side of the assignment operator, you are subtracting two time points (now() and start), and assigning to end.

Logically, if you subtract two time points, you do not obtain a new time point. For instance, if I wanted to subtract "08:15:00 today" - "08:05:00 today", it would not make sense to describe the result as "00:10:00 today". Instead, the C++ chrono library has a duration class template; it is intended to represent lengths of time (e.g. the difference between two time points).

See the operator - overload number 4 here: http://en.cppreference.com/w/cpp/chrono/time_point/operator_arith2

I suggest watching the tutorial video that @Howard Hinnant linked to above... Mr. Hinnant was involved in developing the std::chrono and boost::chrono libraries.

A potential second issue is that start has type std::chrono::system_clock::time_point, which may be a different type (different clock) than the type returned by std::chrono::high_resolution_clock::now() (which has type std::chrono::high_resolution_clock::time_point).

like image 144
NicholasM Avatar answered Feb 06 '23 19:02

NicholasM