命名空间
变体
操作

std::chrono::round(std::chrono::time_point)

来自 cppreference.cn
< cpp‎ | chrono‎ | time point
 
 
 
 
定义于头文件 <chrono>
template< class ToDuration, class Clock, class Duration >

constexpr std::chrono::time_point<Clock, ToDuration>

    round( const std::chrono::time_point<Clock, Duration>& tp );
(自 C++17 起)

返回最接近 tp 且可使用 ToDuration 表示的时间点,在中间情况下向偶数舍入。

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

内容

[编辑] 参数

tp - 要舍入到最近的时间点

[编辑] 返回值

tp 舍入到使用 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 Clock, class FromDuration,
         class = std::enable_if_t<detail::is_duration_v<To> &&
                !std::chrono::treat_as_floating_point_v<typename To::rep>>>
constexpr std::chrono::time_point<Clock, To> round(
    const std::chrono::time_point<Clock, FromDuration>& tp)
{
    return std::chrono::time_point<Clock, To>{
        std::chrono::round<To>(tp.time_since_epoch())};
}

[编辑] 示例

#include <chrono>
#include <iostream>
#include <string>
 
template<typename TimePoint>
std::string to_string(const TimePoint& time_point)
{
    return std::to_string(time_point.time_since_epoch().count());
}
 
int main()
{
    using namespace std::literals::chrono_literals;
    using Sec = std::chrono::seconds;
 
    std::cout << "Time point\t" "Cast\t" "Floor\t" "Round\t" "Ceil\n";
    std::cout << "(ms)\t\t"     "(s)\t"  "(s)\t"   "(s)\t"   "(s)\n";
    for (const auto value_ms : {5432ms, 5678ms})
    {
        std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>
            time_point_ms(value_ms);
 
        std::cout
            << to_string(time_point_ms) << "\t\t"
            << to_string(std::chrono::time_point_cast<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::floor<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::round<Sec>(time_point_ms)) << '\t'
            << to_string(std::chrono::ceil<Sec>(time_point_ms)) << '\n';
    }
}

输出

Time point	Cast	Floor	Round	Ceil
(ms)		(s)	(s)	(s)	(s)
5432		5	5	5	6
5678		5	5	6	6

[编辑] 参见

将时间点转换为同一时钟上的另一个时间点,但具有不同的时长
(函数模板) [编辑]
将 time_point 转换为另一个,向上舍入
(函数模板) [编辑]
将 time_point 转换为另一个,向下舍入
(函数模板) [编辑]
将 duration 转换为另一个,舍入到最近, ties to even
(函数模板) [编辑]
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
最近的整数,在中间情况下远离零舍入
(函数) [编辑]