2

boost::timer::cpu_timer用来计算算法的“用户处理时间”,如下所示:

boost::timer::cpu_timer timer;

boost::timer::nanosecond_type userTime = timer.elapsed().user;

userTime我的问题是如何格式化HH::MM::SS.mmm格式?我知道我可以自己编写代码,但我期待 Boost 提供一些方法来做到这一点。

我遇到了这个例子,但它使用了boost::chrono::duration<Rep, Period>,我不知道如何从boost::timer::nanosecond_type.

4

1 回答 1

2

您需要转换nanosecond_type为.durationtime_point

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

namespace chrono = boost::chrono;

int main()
{
    // get now time & start timer
    chrono::system_clock::time_point start_time = chrono::system_clock::now();
    boost::timer::cpu_timer timer;

    for (int i = 0; i < 100000; ++i) {}

    // elapsed time conversion to time_point
    chrono::system_clock::time_point end_time
        = chrono::time_point_cast<chrono::system_clock::duration>(
                start_time + chrono::nanoseconds(timer.elapsed().user));

    // time_point conversion to time_t&tm
    std::time_t time = chrono::system_clock::to_time_t(end_time);
    std::tm* t = std::localtime(&time);

    // formatting
    std::size_t fractional_seconds = chrono::duration_cast<chrono::milliseconds>(
                                        end_time.time_since_epoch()
                                     ).count() % 1000;
    std::string s = (boost::format("%d:%d:%d.%d")
                        % t->tm_hour
                        % t->tm_min
                        % t->tm_sec
                        % fractional_seconds
                    ).str();
    std::cout << s << std::endl;
}

可能的输出:

10:42:55.445
于 2013-04-23T01:43:07.843 回答