'How do I average std::chrono::time_point? [duplicate]
Given a vector of std::chrono::time_point<Rep, Period>, how do I find the average time_point?
The usual algorithm to find an average (add all values with std::accumulate, divide by the vector size) does not work because you can't add two std::chrono::time_point values, nor can you divide a std::chrono::time_point<Rep, Period> by vec.size()
Solution 1:[1]
You have to do the calculation in terms of a std::chrono::duration, such as time_since_epoch.
template<typename TimePoint>
TimePoint mean(auto&& range) {
auto as_duration = std::views::transform(range, [](auto & tp){ return tp.time_since_epoch(); });
return { std::accumulate(std::begin(as_duration), std::end(as_duration), {}) / std::size(range) };
}
Solution 2:[2]
Difference between two time points is std::chrono::duration, and these types you can sum. So just take difference to the first element, averagize, and add the average to the first element. You'll get average timepoint.
Just make sure the durations you get don't get overflown after summing up. Consider casting to std::chrono::duration<double> but it might be over cautious.
Instead of taking difference vs first element you can also use time_since_epoch() but I don't recommend.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
