命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | chrono‎ | duration
 
 
 
 
定义于头文件 <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)。

当且仅当 ToDurationstd::chrono::duration 的特化,且 std::chrono::treat_as_floating_point_v<typename ToDuration::rep>false 时,此函数才参与重载决议。

目录

[编辑] 参数

d - 要转换的 duration

[编辑] 返回值

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

[编辑] 参阅

将一个 duration 转换为另一个,具有不同的时钟间隔
(函数模板) [编辑]
将一个 duration 转换为另一个,向下取整
(函数模板) [编辑]
将一个 duration 转换为另一个,向上取整
(函数模板) [编辑]
将一个 time_point 转换为另一个,四舍五入到最接近的值,平局时取偶数
(函数模板) [编辑]
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
最接近整数,在半数情况下远离零舍入
(函数) [编辑]