Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

period must be a specialization of ratio in C++17 chrono library?

Tags:

c++

c++17

chrono

I'm clearly too stupid to use the C++17 <chrono> library. Compiling the following...

#include <chrono>
#include <iostream>

int main() {
    using clock = std::chrono::steady_clock;
    using duration = std::chrono::duration<double, std::chrono::seconds>;
    using timepoint = std::chrono::time_point<clock, duration>;
    timepoint t0 = clock::now();
    for (int i = 0; i < 1000; i++) {
        timepoint t = clock::now();
        duration d = t-t0;
        double seconds = d.count();
        std::cout << seconds << std::endl;
    }
}

I get...

/usr/include/c++/8/chrono:319:16: error: static assertion failed:
                                  period must be a specialization of ratio
      static_assert(__is_ratio<_Period>::value,
                    ^~~~~~~~~~~~~~~~~~~

Any ideas?

like image 578
Andrew Tomazos Avatar asked Feb 18 '19 05:02

Andrew Tomazos


1 Answers

The second type parameter to std::chrono::duration needs to be a ratio (ticks per second), not another duration (see https://en.cppreference.com/w/cpp/chrono/duration). std::chrono::seconds is a duration. You'd want this instead:

using duration = std::chrono::duration<double, std::ratio<1> >;

FYI std::chrono::seconds is basically a std::chrono::duration<some integer type, std::ratio<1> >; your duration type is sort of like seconds but with a floating point number instead of an integer.

like image 192
Jason C Avatar answered Sep 30 '22 04:09

Jason C