Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created December 30, 2011 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/1539705 to your computer and use it in GitHub Desktop.
Save maraigue/1539705 to your computer and use it in GitHub Desktop.
[C++][Linux] clock関数でベンチマークを取ろうとしたのだが、結果が測定箇所以外に書かれたコードに大幅に依存してしまう
#include <iostream>
#include <ctime>
long long int factorial(long long int x){
if(x <= 1) return 1;
return(x * factorial(x - 1));
}
int main(void){
clock_t sum1 = 0, sum2 = 0, begin, end;
long long int i, j, result;
for(i = 0; i < 10000; i++){
begin = std::clock(); // ベンチマーク開始
for(j = 0; j < 10000; j++){
result = factorial(j % 20);
}
end = std::clock(); // ベンチマーク終了
sum1 += (end - begin);
// ---------- ここが問題の箇所 ----------
//std::cerr << result << std::endl;
begin = std::clock(); // ベンチマーク開始
for(j = 0; j < 10000; j++){
result = factorial(j % 20);
}
end = std::clock(); // ベンチマーク終了
sum2 += (end - begin);
}
std::cout << "Time(1): " << sum1 << std::endl;
std::cout << "Time(2): " << sum2 << std::endl;
}
/*
実験条件
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Ubuntu 11.10
Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
実験結果
"std::cerr << result << std::endl;" をコメントアウトした場合
Time(1): 5750000 5990000 5640000 5660000 5970000 (平均:5802000)
Time(2): 6190000 5880000 6260000 6190000 5910000 (平均:6086000)
"std::cerr << result << std::endl;" をコメントアウトしなかった場合
Time(1): 1400000 2050000 1300000 1350000 1280000 (平均:1476000)
Time(2): 520000 580000 460000 540000 510000 (平均: 522000)
"std::cerr << result << std::endl;" をコメントアウトしなかったものの、
./a.out 2&>/dev/null と実行した場合
Time(1): 5840000 5680000 5700000 5800000 5440000 (平均:5692000)
Time(2): 5580000 5720000 5730000 5630000 5800000 (平均:5692000)
疑問点
(i)clock関数はCPU時間で測っているらしい(Linuxの場合)のだが、
なぜベンチマークを取っている部分と関係ない部分に挿入された
std::cerrによって、ベンチマーク部分の所要時間が減るという
結果になるのか。
(ii)またその場合、Time(1)(std::cerrを使った部分より前)よりも
Time(2)(std::cerrを使った部分の直後)の方が所要時間が
減るのはどういう原理なのか。
補足
getrusage(リソース仕様量を得る、Unix系のみで使える?関数)を使っても
似た結果でした。
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment