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

< cpp‎ | chrono‎ | time point
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
日期和时间工具
(C++11)
(C++11)
当天时刻
(C++20)



(C++20)(C++20)(C++20)(C++20)
时钟
(C++20)
                                             
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
日历
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
时区
(C++20)
(C++20)
(C++20)
(C++20)
C 风格日期和时间
 
 
定义于头文件 <chrono>
template <class ToDuration, class Clock, class Duration>
constexpr time_point<Clock, ToDuration> round(const time_point<Clock, Duration>& tp);
(C++17 起)

返回能以 ToDuration 表示的最接近 tp 的时间点,中点情况下向偶数舍入。

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

参数

tp - 要舍入到最近值的 time_point

返回值

舍入到使用 ToDuration 类型时长的最近时间点的 tp ,中点情况下向偶数舍入。

可能的实现

template <class T> struct is_duration : std::false_type {};
template <class Rep, class Period> struct is_duration<
    std::chrono::duration<Rep, Period>> : std::true_type {};
 
template <class To, class Clock, class FromDuration,
          class = std::enable_if_t<is_duration<To>{}
             && !std::chrono::treat_as_floating_point<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 <iostream>
#include <chrono>
#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 到另一个,向下取整
(函数模板)
转换时长到另一个时长,就近取整,偶数优先
(函数模板)
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
最接近整数,中间情况下向远离零舍入
(函数)