Formatting time with boost chrono

1.7k views Asked by At

I wonder if is there any way to get only the time without printing out the units :

#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";        
}

the Output is :

123 milliseconds 

I'd like to get only

123

Any solutions ?

1

There are 1 answers

2
mastov On BEST ANSWER

milliseconds is a template instantiation of the duration class template:

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

The stream output operator << is overloaded for the duration class:

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

Given the template parameters of your case, the provided version by default adds the unit "milliseconds" as text.

But the duration class has the method count that will return you the duration in the specified unit (in your case milliseconds) as the specified integer type (the rep type parameter, in your case boost::int_least64_t):

constexpr rep count() const;

You can output that integer number in your own format (in your case just the pure number):

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