つまり、CPUが関数の実行に費やした時間と、関数の実行にかかるウォールクロックの時間をどのようにして計測することができますか?(Linux/Windows、x86とx86_64の両方に興味があります)。私がやりたいことを見てみましょう(ここではC++を使っていますが、Cのソリューションの方がいいでしょう)。
int startcputime, endcputime, wcts, wcte;
startcputime = cputime();
function(args);
endcputime = cputime();
std::cout << "it took " << endcputime - startcputime << " s of CPU to execute this\n";
wcts = wallclocktime();
function(args);
wcte = wallclocktime();
std::cout << "it took " << wcte - wcts << " s of real time to execute this\n";
**もう一つの重要な質問:このタイプの時間測定は、アーキテクチャに依存しないのでしょうか?
ここでは、WindowsとLinux、CとC++の両方に対応した、コピーペーストによるソリューションを紹介します。
コメントにもあるように、これを実現するboostライブラリがあります。しかし、もしboostが使えなくても、この方法は使えるはずです。
// Windows
#ifdef _WIN32
#include <Windows.h>
double get_wall_time(){
LARGE_INTEGER time,freq;
if (!QueryPerformanceFrequency(&freq)){
// Handle error
return 0;
}
if (!QueryPerformanceCounter(&time)){
// Handle error
return 0;
}
return (double)time.QuadPart / freq.QuadPart;
}
double get_cpu_time(){
FILETIME a,b,c,d;
if (GetProcessTimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}else{
// Handle error
return 0;
}
}
// Posix/Linux
#else
#include <time.h>
#include <sys/time.h>
double get_wall_time(){
struct timeval time;
if (gettimeofday(&time,NULL)){
// Handle error
return 0;
}
return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
double get_cpu_time(){
return (double)clock() / CLOCKS_PER_SEC;
}
#endif
これらのクロックを実装する方法はたくさんあります。しかし、上のスニペットが使用しているのは以下の通りです。
Windowsの場合。
GetProcessTimes()
.Linuxの場合
gettimeofday()
][3]clock()
][4]ちょっとしたデモをご覧ください。
#include <math.h>
#include <iostream>
using namespace std;
int main(){
// Start Timers
double wall0 = get_wall_time();
double cpu0 = get_cpu_time();
// Perform some computation.
double sum = 0;
#pragma omp parallel for reduction(+ : sum)
for (long long i = 1; i < 10000000000; i++){
sum += log((double)i);
}
// Stop timers
double wall1 = get_wall_time();
double cpu1 = get_cpu_time();
cout << "Wall Time = " << wall1 - wall0 << endl;
cout << "CPU Time = " << cpu1 - cpu0 << endl;
// Prevent Code Elimination
cout << endl;
cout << "Sum = " << sum << endl;
}
出力(12スレッド)。
Wall Time = 15.7586
CPU Time = 178.719
Sum = 2.20259e+011
具体的な例として、@lip'さんが提案した「できればboost::timer
を使ってください」を挙げておきます(Boost 1.51でテスト済み)。
#include <boost/timer/timer.hpp>
// this is wallclock AND cpu time
boost::timer::cpu_timer timer;
... run some computation ...
boost::timer::cpu_times elapsed = timer.elapsed();
std::cout << " CPU TIME: " << (elapsed.user + elapsed.system) / 1e9 << " seconds"
<< " WALLCLOCK TIME: " << elapsed.wall / 1e9 << " seconds"
<< std::endl;
time.h]1のclock
メソッドを使用します。
clock_t start = clock();
/* Do stuffs */
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
残念ながら、このメソッドはLinuxではCPU時間を返しますが、Windowsでは壁時計の時間を返します(この情報を提供してくれたコメントに感謝します)。