多个ptime的平均值

时间:2016-09-13 14:36:50

标签: c++ boost posix

我试图找到调用函数的平均UTC时间。所以我这样做:

    boost::posix_time::ptime  current_time_before(boost::posix_time::microsec_clock::universal_time());
    DoStuff();
    boost::posix_time::ptime current_time_after(boost::posix_time::microsec_clock::universal_time());

如何计算这两次之间的平均值? 我试过了:

double time_avg = (current_time_before+current_time_after)*0.5;

但我在Linux系统上遇到错误,似乎有“+”但不是“ - ”的问题。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

只是......自然地写下来?

ptime midpoint(ptime const& a, ptime const& b) {
    return a + (b-a)/2; // TODO check for special case `b==a`
}

现场演示:

<强> Live On Coliru

#include <boost/date_time/posix_time/posix_time.hpp>

using boost::posix_time::ptime;

ptime midpoint(ptime const& a, ptime const& b) {
    return a + (b-a)/2;
}

int main() {

    ptime a = boost::posix_time::second_clock::local_time();
    ptime b = a + boost::posix_time::hours(3);

    std::cout << "Mid of " << a << " and " << b << " is " << midpoint(a,b) << "\n";
    std::swap(a,b);
    std::cout << "Mid of " << a << " and " << b << " is " << midpoint(a,b) << "\n";
}

打印

Mid of 2016-Sep-15 11:17:10 and 2016-Sep-15 14:17:10 is 2016-Sep-15 12:47:10
Mid of 2016-Sep-15 14:17:10 and 2016-Sep-15 11:17:10 is 2016-Sep-15 12:47:10
相关问题