概要
注意点
機種依存コードを排除したかったので、時間計測にはboostライブラリを使用しています。
また、long longを使用して1億回のループを行っています。long longで1億を表せない環境では、このプログラムは正常に動作しません。
コード
#include <iostream> #include <string> #include <boost/timer.hpp> using namespace std;
namespace { const long long MAX_REPEAT_SWAP_OF_STRING = 100000000; }
int main() { string a = "1"; string b = "2"; { cout << "Swap performance check (std::string - manual)" << endl; cout << " - repeat num : " << MAX_REPEAT_SWAP_OF_STRING << endl; cout << endl; cout << "Count Start !! " << endl;
boost::timer t; for (long long i = 0; i < MAX_REPEAT_SWAP_OF_STRING; i++) { string tmp = a; a = b; b = tmp; } double elapsed = t.elapsed(); cout << "Count End !! " << endl; cout << endl;
cout << "elapsed : " << elapsed << endl; cout << "average : " << elapsed / MAX_REPEAT_SWAP_OF_STRING << endl; } { cout << "Swap performance check (std::string - using std::string::swap)" << endl; cout << " - repeat num : " << MAX_REPEAT_SWAP_OF_STRING << endl; cout << endl; cout << "Count Start !! " << endl;
boost::timer t; for (long long i = 0; i < MAX_REPEAT_SWAP_OF_STRING; i++) { a.swap(b); } double elapsed = t.elapsed(); cout << "Count End !! " << endl; cout << endl;
cout << "elapsed : " << elapsed << endl; cout << "average : " << elapsed / MAX_REPEAT_SWAP_OF_STRING << endl; } cout << endl << endl;
return 0; }
実行例
Swap performance check (std::string - manual) - repeat num : 100000000
Count Start !! Count End !!
elapsed : 18.953 average : 1.8953e-007 Swap performance check (std::string - using std::string::swap) - repeat num : 100000000
Count Start !! Count End !!
elapsed : 4.125 average : 4.125e-008