c++c++-chronounits-of-measurementfmt

Is there a less verbose way of expressing duration in ms and hours?


This C++ snippet prints a duration in ms and hours:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;
using namespace std::chrono;

int main() {
  auto t0 = high_resolution_clock::now();
  this_thread::sleep_for(300ms);
  auto t1 = high_resolution_clock::now();
  cout << duration<float, milli>{t1-t0}.count() << "\n";
  cout << duration<float, ratio<3600>>{t1-t0}.count() << "\n";
}

Is there a less cumbersome and more concise way of expressing this duration in various time units? ratio<3600> seems especially clunky. I'd rather have something with hour in it. Also, I prefer an option, which plays nicely with current fmt library (https://fmt.dev/10.2.0/). For example, t1-t0 works fine with iostream, but not with fmt.

I've spent time looking at and experimenting with time units based on https://en.cppreference.com/w/cpp/chrono/duration and all I got were numerous and long template barfs. No clue why someone decided that duration<float, hour> is not a good analog of duration<float, milli>.


Solution

  • chrono has these aliases for integral representations:

    If you want a floating-point representation then you'll have to define similar aliases yourself, e.g.

    using float_milliseconds = std::chrono::duration<float, std::milli>;
    

    As suggested by Howard, for hours you can use hours::period which is more intuitive than ratio<3600>.

    This can be done once and reused.

    Both your durations work fine with the latest version of {fmt}: https://www.godbolt.org/z/ssorhqMPY.