Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting time_point to specific duration with chrono

Tags:

c++

c++11

/*definition of start and end
std::chrono::time_point<std::chrono::system_clock> start;
std::chrono::time_point<std::chrono::system_clock> _end;
*/

std::chrono::time_point<std::chrono::system_clock> someclass::spf()
{
    _end = std::chrono::system_clock::now();
    std::chrono::time_point<std::chrono::system_clock> time(_end-start);
    start = std::chrono::system_clock::now();
    return time;
}
unsigned int someclass::secs()
{
    return std::chrono::duration_cast<std::chrono::seconds>(spf()).count();
}

Compiler gives me errors for the call of duration_cast. Exact error:

error: no matching function for call to ‘duration_cast(std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >)’
like image 950
NaCl Avatar asked Feb 06 '14 23:02

NaCl


1 Answers

A time point (std::chrono::time_point<...>) is not a duration (std::chrono::duration<...>, like std::chrono::seconds for example which is a typedef).

They are different types.

You are trying to cast a duration, but spf returns a time_point. A duration is the time between 2 time_point. So to get a duration from a time_point, you need another time_point and get the duration between these time_points.

So here your error is both in spf returning a time_point instead of a duration, and this line is wrong:

std::chrono::time_point<std::chrono::system_clock> time(_end-start);

You obviously want a duration, but build a time_point. Do this instead:

const auto time_since_start = _end - start;
//...
return time_since_start; // you might need a duration cast here depending on what spf() will return.

So the return type of spf() have to be a duration, like seconds or milliseconds or whatever your want.

like image 138
Klaim Avatar answered Sep 30 '22 11:09

Klaim