gpt4 book ai didi

c++ - 多个 ptime 的平均值

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:50 25 4
gpt4 key购买 nike

我正在尝试查找调用函数时的平均 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com