【问题标题】:Formatting time with boost chrono使用 boost chrono 格式化时间
【发布时间】:2015-06-18 11:56:15
【问题描述】:

我想知道是否有任何方法可以只获取时间而不打印单位:

#include <boost/chrono.hpp>
#include <iostream>

boost::chrono::milliseconds sumGlobal;

int main() {
    boost::chrono::high_resolution_clock::time_point t1 ;
    boost::chrono::high_resolution_clock::time_point t2 ;

    for (i=0;i<10;i++)
    { 
        t1 = boost::chrono::high_resolution_clock::now();
        f(); //to waste time   
        t2 = boost::chrono::high_resolution_clock::now();
        sumGlobal += (boost::chrono::duration_cast<boost::chrono::milliseconds>(t2-t1)); 
    }          

    std::cout << sumGlobal << "\n";        
}

输出是:

123 milliseconds 

我只想要一个

123

有什么解决办法吗?

【问题讨论】:

  • TIL boost chrono 时间单位有超载的流式操作符。我想知道本地化和其他事情(如简化、多元化)

标签: c++ boost boost-units


【解决方案1】:

millisecondsduration 类模板的模板实例化:

typedef duration<boost::int_least64_t, milli> milliseconds;

流输出运算符&lt;&lt;duration 类重载:

template <class CharT, class Traits, class Rep, class Period>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os, const duration<Rep, Period>& d);

给定您案例的模板参数,提供的版本默认添加单位“毫秒”作为文本。

但是duration class 具有count 方法,它将以指定的单位(在您的情况下为毫秒)作为指定的整数类型返回您的持续时间(rep 类型参数,在您的情况下为boost::int_least64_t) :

constexpr rep count() const;

您可以以自己的格式输出该整数(在您的情况下只是纯数字):

std::cout << sumGlobal.count() << std::endl;

【讨论】:

  • “你无能为力”不是真的;使用自定义duration_units facets 有很多可定制性
  • @sehe:编辑为更谨慎的声明。
猜你喜欢
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多