跳转至

性能分析

在 Linux 下,我们可以使用 gprof 工具分析 C++ 程序中各个函数的运行总时间,从而高效的进行常数优化。

使用方法

test.cpp

#include<iostream>
#include<random>
using namespace std;

int k = (random_device){}();

int f(int n) {
    int x = n;
    for(int i = 1; i <= 1000000000; i++) x ^= i;
    return x;
}

int g() {
    int x = 0;
    for(int i = 2; i <= 1000000001; i++) x ^= i;
    return f(k) + f(k + 1) + x;
}

int main() {

    cout << f(k - 1) << endl;
    cout << g() << endl;

    return 0;
}

bash

g++ test.cpp -o a -pg
./a
gprof a gmon.out > gp.out

gp.out

Flat profile:

Each sample counts as 0.01 seconds.
%   cumulative   self              self     total           
time   seconds   seconds    calls   s/call   s/call  name    
75.80      4.93     4.93        3     1.64     1.64  f(int)
25.11      6.57     1.63        1     1.63     4.92  g()
0.00      6.57     0.00        1     0.00     0.00  _GLOBAL__sub_I_k
0.00      6.57     0.00        1     0.00     0.00  __static_initialization_and_destruction_0(int, int)
0.00      6.57     0.00        1     0.00     0.00  std::random_device::random_device()
0.00      6.57     0.00        1     0.00     0.00  std::random_device::~random_device()
0.00      6.57     0.00        1     0.00     0.00  std::random_device::operator()()
%time self seconds calls selfs/call totals/calls
该函数花费的时间 占总时间百分比 该函数花费的时间 调用次数 平均花费时间 平均花费时间(包含它调用的其它函数)

其中 %timeself seconds 以及 selfs/calls 不会计量它调用的其它函数。