c++ - 如何在 Linux/Windows 上测量 CPU 时间和挂钟时间?

标签 c++ c performance time cpu

我的意思是:如何测量 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:

对于 Linux:


这是一个小演示:

#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

关于c++ - 如何在 Linux/Windows 上测量 CPU 时间和挂钟时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17432502/

相关文章:

sql - NULL 与 NOT NULL 性能差异

java - 添加更多 Controller 时,Spring mvc 性能显着下降

c++ - 删除数组时断言失败

c++ - 单独的类文件错误?

c++ - 将字符串和变量打印到 glwindow

c - 如何防止scanf导致C语言缓冲区溢出?

c++ - 我的 RichEdit 控件可以包含可点击的链接吗?

c - 在我的读取函数 myread 中,当我执行 cat/driver/mydriver 时,它会不断打印读取的数据。我只需要打印一次如何做到这一点

c++ - C/C++ 中超大静态数组的算术运算

java - 在容量为 M 的 K 个房间中分配 N 吨食物