I am trying to find the average UTC time of when a function was called. So I do:
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());
How do I go about calculating the averages between these two times? I tried:
double time_avg = (current_time_before+current_time_after)*0.5;
But I get an error on a linux system that seems to have a problem with "+" but not "-" .
Thank you for your help.
Just... write it naturally?
ptime midpoint(ptime const& a, ptime const& b) {
return a + (b-a)/2; // TODO check for special case `b==a`
}
Live demo:
#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";
}
Prints
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