我正在尝试查找调用函数时的平均 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`
}
现场演示:
#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/