多个 ptime 的平均值

Average of multiple ptime

我正在尝试查找调用函数时的平均 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 系统上遇到错误,似乎“+”有问题,但“-”没有问题。

感谢您的帮助。

就是……写的自然一点?

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