boost :: chrono可读持续时间

时间:2013-10-25 09:58:04

标签: c++ boost

我一直在研究一个使用boost chrono在微秒内运行的分析器,它适用于小功能,但我倾向于使用更大的功能获得非常高的数字。

想象一下以下场景

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;

输出将如下所示

  
    

us1:300 us,us2:200000 us

  

这可能变得难以量化所以我想知道是否有一种方法可以舍入到更高的单位,以便输出看起来像

  
    

us1:300 us,us2:200 ms

  

1 个答案:

答案 0 :(得分:3)

感谢大家,我解决了这个问题:

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();
}

可能值得制作静态流,但你会得到一般的想法