duration转换为人类可读的时间

duration转换为人类可读的时间

本文介绍了将std :: duration转换为人类可读的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在将 std :: duration 打印为人类可读的持续时间的标准实现?

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"

或类似的东西.

推荐答案

同意没有标准实现.这是您自己写一个的方法:

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

这篇关于将std :: duration转换为人类可读的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 19:42