简体   繁体   English

boost :: chrono可读持续时间

[英]boost::chrono readable duration

I have been working on a profiler that times functions in microseconds using boost chrono and it works well for small functions but I tend to get very high number with bigger ones. 我一直在研究一个使用boost chrono在微秒内运行的分析器,它适用于小功能,但我倾向于使用更大的功能获得非常高的数字。

Imagine the following scenario 想象一下以下场景

boost::chrono::duration<long long, boost::micro> us1(300);
boost::chrono::duration<long long, boost::micro> us2(200000);

std::cout << boost::chrono::duration_short << "us1: " << us1 << ", us2: " << us2;

The output will look like this 输出将如下所示

us1: 300 us , us2: 200000 us us1:300 us,us2:200000 us

which can become hard to quantify so i'd like to know if there is a way to round to the higher unit so that the output can look like 这可能变得难以量化,所以我想知道是否有一种方法可以舍入到更高的单位,以便输出看起来像

us1: 300 us , us2: 200 ms us1:300 us,us2:200 ms

Thanks to everyone, I solved it that way: 感谢大家,我解决了这个问题:

const std::string readableDuration(const boost::chrono::duration<long long, boost::micro>& duration)
{
    std::stringstream stream;
    int digits = calcNumDigits(duration.count());

    stream << boost::chrono::duration_short;

    if (digits <= 3) {
        stream << duration;
    } else if ((digits > 3) && (digits <= 6)) {
        stream << boost::chrono::duration_cast<boost::chrono::milliseconds>(duration);
    } else if ((digits > 6) && (digits <= 9)) {
        stream << boost::chrono::duration_cast<boost::chrono::seconds>(duration);
    } else if (digits > 9)
    {
        stream << boost::chrono::duration_cast<boost::chrono::minutes>(duration);
    }

    return stream.str();
}

Might be worth making stream static but you get the general idea 可能值得使流静态,但你得到了一般的想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM