1

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

#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

有什么解决办法吗?

4

1 回答 1

2

millisecondsduration类模板的模板实例化:

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

流输出运算符<<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);

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

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

constexpr rep count() const;

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

std::cout << sumGlobal.count() << std::endl;
于 2015-06-18T12:17:04.777 回答