简体   繁体   English

如何获得几个chrono :: time_points的平均值

[英]How to get the average of several chrono::time_points

The formula for getting the average of several numbers is of course well known: 获得几个数字的平均值的公式当然是众所周知的:

And this formula can easily be used to get the average of chrono::duration s: 这个公式可以很容易地用来获得chrono::duration s的平均值:

template <class Rep0, class Period0>
auto
sum(const std::chrono::duration<Rep0, Period0>& d0)
{
    return d0;
}

template <class Rep0, class Period0, class ...Rep, class ...Period>
auto
sum(const std::chrono::duration<Rep0, Period0>& d0,
    const std::chrono::duration<Rep, Period>& ...d)
{
    return d0 + sum(d...);
}

template <class ...Rep, class ...Period>
auto
avg(const std::chrono::duration<Rep, Period>& ...d)
{
    return sum(d...) / sizeof...(d);
}

But chrono::time_point s can't be added to one another. 但是chrono::time_point s不能互相添加。 How can I average time_point s? 我怎样才能平均time_point

It helps to start out with the assumption that you can add time_point s, and then manipulate the formula to eliminate those additions: 它有助于开始假设您可以添加time_point ,然后操纵公式以消除这些添加:

First separate out t 1 from the sum: 首先从总和中分出t 1

Next both add and subtract t 1 : 接下来加上减去t 1

Factor and rearrange: 因素和重新排列:

And then, since you are subtracting t 1 the same number of times as you are summing, you can include that into the sum: 然后,由于你在求和时减去t 1的次数相同,你可以将它包含在总和中:

Now you are summing duration s instead of time_point s! 现在你总结duration s 而不是 time_point s! As we already have a function to sum duration s, averaging time_point s can easily build on that: 由于我们已经有一个总和duration s的函数,平均time_point可以很容易地建立在:

template <class Clock, class Duration0, class ...Duration>
auto
avg(const std::chrono::time_point<Clock, Duration0>& t0,
    const std::chrono::time_point<Clock, Duration>& ...t)
{
    return t0 + sum((t - t0)...) / (1 + sizeof...(t));
}

Averaging a single time_point is a special case since sum of duration s does not handle summing zero duration s (what would be the units?). 平均单个time_point是一种特殊情况,因为duration s的sum不处理零duration s的总和(单位是什么?)。 So an overload for that case is easily added: 因此,很容易添加该案例的重载:

template <class Clock, class Duration0>
auto
avg(const std::chrono::time_point<Clock, Duration0>& t0)
{
    return t0;
}

This is written in C++14. 这是用C ++ 14编写的。 It can be coded in C++11, using the trailing return type declaration syntax, which is more verbose, but completely doable. 它可以使用尾随返回类型声明语法在C ++ 11中编码,该语法更详细,但完全可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM