Namespaces
Variants

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

From cppreference.net
定義済みヘッダー <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 で表現可能な値であり、中間値の場合には偶数への丸めを行います。

この関数は、以下の条件が満たされない限りオーバーロード解決に参加しません: 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

関連項目

同じクロック上の異なるdurationを持つ別のtime_pointに変換する
(関数テンプレート)
time_pointを別のtime_pointに変換し、切り上げを行う
(関数テンプレート)
time_pointを別のtime_pointに変換し、切り捨てを行う
(関数テンプレート)
durationを別のdurationに変換し、最も近い値に丸め、中間値は偶数方向に丸める
(関数テンプレート)
(C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11)
最も近い整数に丸め、中間値はゼロから遠ざかる方向に丸める
(関数)