LoginSignup
42
28

More than 5 years have passed since last update.

(c++11)chronoを用いた時間計測(タイムスタンプのとり方)

Posted at

(c++11)How to use "chrono(c++11)" for timestamp.

Abstract

chronoとは, c++11で追加された精度に優れた時間ライブラリであり, gccやclangだけではなくvisual studioでも用いることができる.
しかし, 一方でchronoの扱いづらさの指摘もある.

本の虫: C++11の時間ライブラリ: chrono

問題は、これらのコンセプトを学ぶのに、労力がかかるという事だ。私は規格を読めるし、Boostや標準化委員会での議論の経緯も知っているからいいものの、通常のユーザーがプログラミング言語をただ使うためだけに、規格や規格制定時の議論や背景の理解を必要とするべきではない。

また,"gettimeofday"はLinuxのような処理系で用いられてきた.しかし, gettimeofdayで用いられるtimezone構造体はobsolete(すたれた, 時代遅れの, もはや用いられない)であり( http://man7.org/linux/man-pages/man2/gettimeofday.2.html ), かつOSを制限する.

そこで, chronoを用いた時間計測の簡単化に取り組む.

Chrono

chronoを用いた処理時間の計測の一般的な使い方は以下である.

引用:C++でフリープラットフォームな時間計測

#include <iostream>
#include <chrono>

int main(){
 std::chrono::system_clock::time_point  start, end; // 型は auto で可
 start = std::chrono::system_clock::now(); // 計測開始時間
// 処理
 end = std::chrono::system_clock::now();  // 計測終了時間
 double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); //処理に要した時間をミリ秒に変換

}

型はautoでいいとしても, 関数を覚えたりTemplateを理解していないと使いにくい.
そこで, 以下のようなコードを書きたい.

int main(){
 double start,end;
 start = get_time_sec();
 // 処理
 end = get_time_sec();
 double elapsed=end-start;
}

そのためのget_time_sec()関数は以下のように設計した.

#include <chrono>
using namespace std::chrono;
inline double get_time_sec(void){
    return static_cast<double>(duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count())/1000000000;
}

無理やりstatic_castでキャストしたけどもっといい実装あるかな...
終了

42
28
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
28