問題描述
我的意思是:我如何測量我的 CPU 花在函數執行上的時間以及運行我的函數所需的掛鐘時間?(我對 Linux/Windows 以及 x86 和 x86_64 感興趣).看看我想做什么(我在這里使用 C++,但我更喜歡 C 解決方案):
I mean: how can I measure time my CPU spent on function execution and wall clock time it takes to run my function? (Im interested in Linux/Windows and both x86 and x86_64). See what I want to do (Im using C++ here but I would prefer C solution):
int startcputime, endcputime, wcts, wcte;
startcputime = cputime();
function(args);
endcputime = cputime();
std::cout << "it took " << endcputime - startcputime << " s of CPU to execute this
";
wcts = wallclocktime();
function(args);
wcte = wallclocktime();
std::cout << "it took " << wcte - wcts << " s of real time to execute this
";
另一個重要問題:這種時間測量架構是否獨立?
推薦答案
這是一個適用于 Windows 和 Linux 以及 C 和 C++ 的復制粘貼解決方案.
Here's a copy-paste solution that works on both Windows and Linux as well as C and C++.
正如評論中提到的,有一個 boost 庫可以做到這一點.但是如果你不能使用 boost,這應該可以工作:
As mentioned in the comments, there's a boost library that does this. But if you can't use boost, this should work:
// 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
有很多方法可以實現這些時鐘.但上面的代碼片段使用的是:
There's a bunch of ways to implement these clocks. But here's what the above snippet uses:
對于 Windows:
For Windows:
- Wall Time:性能計數器
- CPU 時間:
GetProcessTimes()
對于 Linux:
- Wall Time:
gettimeofday()
- CPU 時間:
clock()
這是一個小演示:
#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 個線程):
Output (12 threads):
Wall Time = 15.7586
CPU Time = 178.719
Sum = 2.20259e+011
這篇關于如何在 Linux/Windows 上測量 CPU 時間和掛鐘時間?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!