/* 介紹<chrono>
-- 一個精確中立的時間和日期庫
* 時鍾:
*
* std::chrono::system_clock: 依據系統的當前時間 (不穩定)
* std::chrono::steady_clock: 以統一的速率運行(不能被調整)
* std::chrono::high_resolution_clock: 提供最小可能的滴答周期
* (可能是steady_clock或者system_clock的typedef)
*
* std:ratio<>表示時鍾周期,即時間的計量單位
*/
std::ratio<1,10> r; //
cout << r.num << "/" << r.den << endl;
cout << chrono::system_clock::period::num << "/" << chrono::system_clock::period::den << endl;
cout << chrono::steady_clock::period::num << "/" << chrono::steady_clock::period::den << endl;
cout << chrono::high_resolution_clock::period::num << "/" << chrono::high_resolution_clock::period::den << endl;
/*
*
* std:chrono::duration<>: 表示持續的時間
* duration<int, ratio<1,1>> -- 秒數存儲在一個int中 (默認)
* duration<double, ration<60,1>> -- 分鍾數儲存在一個double中
* 庫中定義了如下方便的duration:
* nanoseconds, microseconds, milliseconds, seconds, minutes, hours
* system_clock::duration -- duration<T, system_clock::period>
* T是一個有符號的算術類型, 可以是int或long或其他
*/
chrono::microseconds mi(2745);
chrono::nanoseconds na = mi;
chrono::milliseconds mill = chrono::duration_cast<chrono::milliseconds>(mi); // 當可能發生信息丟失的時候,要顯式地轉換
// 直接截斷,而不是四舍五入
mi = mill + mi; // 2000 + 2745 = 4745
mill = chrono::duration_cast<chrono::milliseconds>(mill + mi); // 6
cout << na.count() << std::endl;
cout << mill.count() << std::endl;
cout << mi.count() << std::endl;
cout << "min: " << chrono::system_clock::duration::min().count() << "\n";
cout << "max: " << chrono::system_clock::duration::max().count() << "\n";
/* std::chrono::time_point<>: 表示一個時間點
* -- 自從一個指定的時間點開始的過去的時間長度:
* 00:00 January 1, 1970 (Corordinated Universal Time - UTC) -- 時鍾的紀元
* time_point<system_clock, milliseconds>: 依據system_clock, 自從紀元開始經過的毫秒數
*
* typdefs
system_clock::time_point -- time_point<system_clock, system_clock::duration>
steady_clock::time_point -- time_point<steady_clock, steady_clock::duration>
*/
// 使用系統時間
chrono::system_clock::time_point tp = chrono::system_clock::now();
cout << tp.time_since_epoch().count() << endl;
tp = tp + seconds(2); // 因為tp精度高,不需要轉換
cout << tp.time_since_epoch().count() << endl;
// 計算時間間隔最好用steady_clock
chrono::steady_clock::time_point start = chrono::steady_clock::now();
cout << "I am bored" << endl;
chrono::steady_clock::time_point end = chrono::steady_clock::now();
chrono::steady_clock::duration d = end - start;
if (d == chrono::steady_clock::duration::zero()) //0時間長度的表示
cout << "no time elapsed" << endl;
cout << duration_cast<microseconds>(d).count() << endl;
// 使用system_clock可能得到不正確的值