Search code examples
c++c++11timec++-chrono

Convert std::duration to human readable time


Is there a standard implementation to print std::duration as a human readable duration?

steady_clock::time_point start = steady_clock::now();
doSomeFoo();
steady_clock::time_point end = steady_clock::now();
std::cout << "Operation took "
          << may_be_std::theMagic(start-end) << std::endl;

Which should print something similar to:

"Operation took 10d:15h:12m:14:s"

or something similar.


Solution

  • Agreed there is no standard implementation. Here is how you can write one yourself:

    #include <iostream>
    #include <iomanip>
    #include <chrono>
    
    std::ostream&
    display(std::ostream& os, std::chrono::nanoseconds ns)
    {
        using namespace std;
        using namespace std::chrono;
        typedef duration<int, ratio<86400>> days;
        char fill = os.fill();
        os.fill('0');
        auto d = duration_cast<days>(ns);
        ns -= d;
        auto h = duration_cast<hours>(ns);
        ns -= h;
        auto m = duration_cast<minutes>(ns);
        ns -= m;
        auto s = duration_cast<seconds>(ns);
        os << setw(2) << d.count() << "d:"
           << setw(2) << h.count() << "h:"
           << setw(2) << m.count() << "m:"
           << setw(2) << s.count() << 's';
        os.fill(fill);
        return os;
    };
    
    int
    main()
    {
        std::cout << "Operation took ";
        display(std::cout, std::chrono::microseconds(918734000000));
        std::cout << '\n';
    }
    
    Operation took 10d:15h:12m:14s