c++ - 多个ptime的平均值

标签 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 系统上遇到一个错误,似乎有“+”问题,但没有“-”问题。

感谢您的帮助。

最佳答案

只是...自然地写?

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

关于c++ - 多个ptime的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39472689/

相关文章:

c++ - getline 不等待输入

c++ - boost::any 需要 RTTI 吗?

linux - .so : need to find out which function(s) are executed on loading

c++ - 迭代器的最佳编码风格

c# - 在 native 可执行文件中嵌入 .net 二进制文件

c++ - BOOST_MOVABLE_BUT_NOT_COPYABLE vs2010 构建错误

c++ - 重载 Boost Multi_Index 查找操作

c - posix在线程中创建共享内存

c - 如何使用 POSIX 按进程父进程返回 cJSON 片段?

c++ - 默认析构函数做了多少