将std :: duration转换为人类可读时间

sor*_*h-r 7 c++ time c++11 c++-chrono

是否有标准实现打印std::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;
Run Code Online (Sandbox Code Playgroud)

哪个应该打印类似于:

"Operation took 10d:15h:12m:14:s"
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

How*_*ant 8

同意没有标准实施.以下是您自己编写的方法:

#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
Run Code Online (Sandbox Code Playgroud)


Tan*_*ash 5

根据霍华德的回答,我写这个是为了确保只打印出相关的数据,所以 120 秒变成了2m00s而不是00d:00h:02m00s,并确保去掉前导零,所以它仍然2m00s和不是02m00s

用法很简单:

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

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

代码:

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();
}
Run Code Online (Sandbox Code Playgroud)