Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 839
sorush-r Avatar asked Mar 23 '14 12:03

sorush-r


1 Answers

Based on Howard's answer, I wrote this to make sure that only the relevant data is printed out, so 120 seconds becomes 2m00s instead of 00d:00h:02m00s, and made sure to strip the leading zero, so its still 2m00s and not 02m00s.

Usage is simple:

std::chrono::seconds seconds{60*60*24 + 61};

std::string pretty_seconds = beautify_duration(seconds);
printf("seconds: %s", pretty_seconds.c_str());
>>seconds: 1d00h01m01s

Code:

std::string beautify_duration(std::chrono::seconds input_seconds)
{
    using namespace std::chrono;
    typedef duration<int, std::ratio<86400>> days;
    auto d = duration_cast<days>(input_seconds);
    input_seconds -= d;
    auto h = duration_cast<hours>(input_seconds);
    input_seconds -= h;
    auto m = duration_cast<minutes>(input_seconds);
    input_seconds -= m;
    auto s = duration_cast<seconds>(input_seconds);

    auto dc = d.count();
    auto hc = h.count();
    auto mc = m.count();
    auto sc = s.count();

    std::stringstream ss;
    ss.fill('0');
    if (dc) {
        ss << d.count() << "d";
    }
    if (dc || hc) {
        if (dc) { ss << std::setw(2); } //pad if second set of numbers
        ss << h.count() << "h";
    }
    if (dc || hc || mc) {
        if (dc || hc) { ss << std::setw(2); }
        ss << m.count() << "m";
    }
    if (dc || hc || mc || sc) {
        if (dc || hc || mc) { ss << std::setw(2); }
        ss << s.count() << 's';
    }

    return ss.str();
}
like image 51
TankorSmash Avatar answered Sep 21 '22 14:09

TankorSmash