Quantcast
Channel: Totem.jp
Viewing all articles
Browse latest Browse all 6

[C++11] std::chrono のメモ

$
0
0

参考: http://cpprefjp.github.io/reference/chrono.html

std::chrono::system_clockは端末の時刻設定に取得できる値が影響されるので、これが嫌な場合(たとえば30分後に実行などのタイムアウト)はstd::chrono::steady_clockを利用する。

[cpp] using namespace std; // 現在の時刻を取得 chrono::time_point<chrono::system_clock> now = chrono::system_clock::now(); chrono::duration<double> timeSinceEpoch = now.time_since_epoch(); double timestamp = timeSinceEpoch.count(); printf("timestamp: %f \n", timestamp); // UNIX時間(秒) // 秒のタイムスタンプならこれで { auto nowInSeconds = duration_cast<seconds>(system_clock::now().time_since_epoch()); uint64_t timestamp = nowInSeconds.count(); } // タイムスタンプから chrono::time_point<chrono::system_clock> に変換 chrono::duration<double> timeSinceEpoch2 = chrono::duration<double>(timestamp); assert(timeSinceEpoch == timeSinceEpoch2); chrono::time_point<chrono::system_clock, decltype(timeSinceEpoch2)> now2(timeSinceEpoch2); assert(now == now2); // 現在の時刻から999ミリ秒後を取得 chrono::time_point<chrono::system_clock> after = chrono::time_point<chrono::system_clock>(now + chrono::milliseconds(999)); // now と after500ms の差を求める chrono::duration<double> diff = after - now; printf("diff.count(): %f \n", diff.count()); // "0.9990000" と出力される chrono::microseconds diffAsMicroSeconds = after - now; printf("diffAsMicroSeconds.count(): %lld \n", diffAsMicroSeconds.count()); // "999000" と出力される chrono::seconds diffAsSeconds = chrono::duration_cast<chrono::seconds>(diff); printf("%lld \n", diffAsSeconds.count()); // "0" と出力される chrono::milliseconds diffAsMilliseconds = chrono::duration_cast<chrono::milliseconds>(diff); printf("%lld \n", diffAsMilliseconds.count()); // "999" と出力される [/cpp]

Viewing all articles
Browse latest Browse all 6