名稱空間
變體
操作

std::chrono::time_point

來自 cppreference.com
< cpp‎ | chrono
 
 
 
 
定義於標頭檔案 <chrono>
template<

    class Clock,
    class Duration = typename Clock::duration

> class time_point;
(C++11 起)

類模板 std::chrono::time_point 表示時間點。其實現如同儲存了 Duration 型別的值,表示從 Clock 紀元開始的時間間隔。

Clock 必須滿足 Clock 的要求 或為 std::chrono::local_t(C++20 起)

(直至 C++23)

目錄

[編輯] 成員型別

成員型別 定義
clock Clock,此時間點所基於的時鐘
duration Duration,一個 std::chrono::duration 型別,用於衡量自紀元以來的時間
rep Rep,一個算術型別,表示時長的“滴答”計數
period Period,一個 std::ratio 型別,表示時長的“滴答”週期

[編輯] 成員函式

構造一個新的時間點
(public 成員函式) [編輯]
返回自其時鐘紀元開始以來的時長作為時間點
(public 成員函式) [編輯]
按給定時長修改時間點
(public 成員函式) [編輯]
增加或減少時長
(public 成員函式) [編輯]
[靜態]
返回對應於最小時長的時間點
(public static 成員函式) [編輯]
[靜態]
返回對應於最大時長的時間點
(public static 成員函式) [編輯]

[編輯] 非成員函式

執行涉及時間點的加法和減法運算
(函式模板) [編輯]
(C++11)(C++11)(在 C++20 中移除)(C++11)(C++11)(C++11)(C++11)(C++20)
比較兩個時間點
(函式模板) [編輯]
將一個時間點轉換為同一時鐘上的另一個時間點,但具有不同的時長
(函式模板) [編輯]
將一個 time_point 轉換為另一個,向下取整
(函式模板) [編輯]
將一個 time_point 轉換為另一個,向上取整
(函式模板) [編輯]
將一個 time_point 轉換為另一個,四捨五入到最接近的值,平局時取偶數
(函式模板) [編輯]

[編輯] 輔助類

特化 std::common_type 特性
(類模板特化) [編輯]
std::chrono::time_point 的雜湊支援
(類模板特化)

[編輯] 示例

#include <algorithm>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
 
void slow_motion()
{
    static int a[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    // Generate Γ(13) == 12! permutations:
    while (std::ranges::next_permutation(a).found) {}
}
 
int main()
{
    using namespace std::literals; // enables literal suffixes, e.g. 24h, 1ms, 1s.
 
    const std::chrono::time_point<std::chrono::system_clock> now =
        std::chrono::system_clock::now();
 
    const std::time_t t_c = std::chrono::system_clock::to_time_t(now - 24h);
    std::cout << "24 hours ago, the time was "
              << std::put_time(std::localtime(&t_c), "%F %T.\n") << std::flush;
 
    const std::chrono::time_point<std::chrono::steady_clock> start =
        std::chrono::steady_clock::now();
 
    std::cout << "Different clocks are not comparable: \n"
                 "  System time: " << now.time_since_epoch() << "\n"
                 "  Steady time: " << start.time_since_epoch() << '\n';
 
    slow_motion();
 
    const auto end = std::chrono::steady_clock::now();
    std::cout
        << "Slow calculations took "
        << std::chrono::duration_cast<std::chrono::microseconds>(end - start) << " ≈ "
        << (end - start) / 1ms << "ms ≈ " // almost equivalent form of the above, but
        << (end - start) / 1s << "s.\n";  // using milliseconds and seconds accordingly
}

可能的輸出

24 hours ago, the time was 2021-02-15 18:28:52.
Different clocks are not comparable:
  System time: 1666497022681282572ns
  Steady time: 413668317434475ns
Slow calculations took 2090448µs ≈ 2090ms ≈ 2s.

[編輯] 亦參見

(C++11)
時間間隔
(類模板) [編輯]
表示特定的 yearmonthday
(類) [編輯]