のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

Boost::Timer 時間計測に使う

Sponsored Links

皆さんこんにちは
お元気ですか。私は元気です。

今日はBoost::Timerについて
C++ではc_clockを使うことで時間を計測することができます。
しかし、

Timer

通常の使い方

#include <iostream>
#include <cmath>
#include <string>
#include <boost/timer/timer.hpp>

using namespace std;

int main(int argc, char const *argv[]){
	boost::timer::cpu_timer timer;

	for(int i = 0; i < 100000000; i++){
		sqrt(3.0);
	}

	string result = timer.format();
	cout << result << endl;
	return 0;
}

実行

g++ timer.cpp -lboost_timer -lboost_system
./a.out
 0.230299s wall, 0.210000s user + 0.000000s system = 0.210000s CPU (91.2%)

CPUの使用時間を表示します。
wall が実際の経過時間、userがユーザーCPU処理時間、systemがシステム関連のCPU処理時間を指しています。

スタート、ストップ、再始動

#include <iostream>
#include <cmath>
#include <string>
#include <boost/timer/timer.hpp>

using namespace std;

int main(int argc, char const *argv[]){
	boost::timer::cpu_timer timer;
	timer.start();
	timer.stop();

	for(int i = 0; i < 100000000; i++){
		sqrt(3.0);
	}

	cout << timer.format() << endl;
	timer.resume();
	for(int i = 0; i < 100000000; i++){
		sqrt(3.0);
	}
	cout << timer.format() << endl;
}

出力

0.000002s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%)

 0.212416s wall, 0.210000s user + 0.000000s system = 0.210000s CPU (98.9%)

startで開始、stopで止める、resumeで再始動を行います。

オブジェクトとして活用

#include <iostream>
#include <cmath>
#include <string>
#include <boost/timer/timer.hpp>

using namespace std;

int main(int argc, char const *argv[]){
	boost::timer::cpu_timer timer;
	for(int i = 0; i < 100000000; i++){
		sqrt(32032);
	}
	boost::timer::cpu_times cpu_object = timer.elapsed();

	cout << "wall:" << cpu_object.wall << endl;
	cout << "user:" << cpu_object.user << endl;
	cout << "system:" << cpu_object.system << endl;
}

boost::timer::cpu_timesオブジェクトを
elapsed()メソッドを使って、取得すると、自由にそのオブジェクトを利用することが出います。

出力

232815662
220000000
0

フォーマットを使う

ソースコード

#include <iostream>
#include <cmath>
#include <string>
#include <boost/timer/timer.hpp>

using namespace std;

int main(int argc, char const *argv[]){
	boost::timer::cpu_timer timer;
	for(int i = 0; i < 100000000; i++){
		sqrt(32032);
	}
	cout << timer.format(4,"経過時間:%w,ユーザーCPU処理時間:%u,プロセスCPU時間%s") << endl;
}

formatの一つ目の引数は4桁表示としうことを示しています。

出力

経過時間:0.2331,ユーザーCPU処理時間:0.2200,プロセスCPU時間0.0000