名稱空間
變體
操作

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

來自 cppreference.com
< 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 起)

返回在 `ToDuration` 中可表示的、最接近 `tp` 的時間點,半進位時向偶數舍入。

此函式不參與過載決議,除非 `ToDuration` 是 std::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 轉換為另一個,四捨五入到最接近的值,平局時取偶數
(函式模板) [編輯]
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
最接近整數,在半數情況下遠離零舍入
(函式) [編輯]