Namespaces
Variants

std::chrono:: round (std::chrono::duration)

From cppreference.net
定义于头文件 <chrono>
template < class ToDuration, class Rep, class Period >
constexpr ToDuration round ( const std:: chrono :: duration < Rep, Period > & d ) ;
(C++17 起)

返回在 ToDuration 中可表示的、最接近 d 的值 t 。若存在两个这样的值,则返回偶数值(即满足 t % 2 == 0 的值 t )。

该函数不参与重载决议,除非 ToDuration std::chrono::duration 的特化,且 std:: chrono :: treat_as_floating_point_v < typename ToDuration :: rep > false

目录

参数

d - 待转换的时间长度

返回值

d 四舍五入到最接近的 ToDuration 类型时长,中间值向偶数取整。

可能的实现

namespace detail
{
    template<class> inline constexpr bool is_duration_v = false;
    template<class Rep, class Period> inline constexpr bool is_duration_v<
        std::chrono::duration<Rep, Period>> = true;
}
template<class To, class Rep, class Period,
         class = std::enable_if_t<detail::is_duration_v<To> &&
                !std::chrono::treat_as_floating_point_v<typename To::rep>>>
constexpr To round(const std::chrono::duration<Rep, Period>& d)
{
    To t0 = std::chrono::floor<To>(d);
    To t1 = t0 + To{1};
    auto diff0 = d - t0;
    auto diff1 = t1 - d;
    if (diff0 == diff1)
    {
        if (t0.count() & 1)
            return t1;
        return t0;
    }
    else if (diff0 < diff1)
        return t0;
    return t1;
}

示例

#include <chrono>
#include <iomanip>
#include <iostream>
int main()
{
    using namespace std::chrono_literals;
    std::cout << "Duration\tFloor\tRound\tCeil\n";
    for (using Sec = std::chrono::seconds;
        auto const d : {+4999ms, +5000ms, +5001ms, +5499ms, +5500ms, +5999ms,
                        -4999ms, -5000ms, -5001ms, -5499ms, -5500ms, -5999ms})
        std::cout << std::showpos << d << "\t\t"
                  << std::chrono::floor<Sec>(d) << '\t'
                  << std::chrono::round<Sec>(d) << '\t'
                  << std::chrono::ceil <Sec>(d) << '\n';
}

输出:

Duration	Floor	Round	Ceil
+4999ms		+4s	+5s	+5s
+5000ms		+5s	+5s	+5s
+5001ms		+5s	+5s	+6s
+5499ms		+5s	+5s	+6s
+5500ms		+5s	+6s	+6s
+5999ms		+5s	+6s	+6s
-4999ms		-5s	-5s	-4s
-5000ms		-5s	-5s	-5s
-5001ms		-6s	-5s	-5s
-5499ms		-6s	-5s	-5s
-5500ms		-6s	-6s	-5s
-5999ms		-6s	-6s	-5s

参见

将时长转换为具有不同滴答间隔的另一种时长
(函数模板)
将时长转换为另一种时长,向下取整
(函数模板)
将时长转换为另一种时长,向上取整
(函数模板)
将时间点转换为另一个时间点,四舍五入到最接近的值,中间值向偶数取整
(函数模板)
(C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11)
最接近的整数,中间情况向远离零的方向舍入
(函数)