c++ - 如何解读perf的报告

标签 c++ c++11 profiler perf

我正在学习如何使用工具 perf 来分析我的 C++ 项目。这是我的代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>


std::mutex mtx;
long long_val = 0;

void do_something(long &val)
{
    std::unique_lock<std::mutex> lck(mtx);
    for(int j=0; j<1000; ++j)
        val++;
}


void thread_func()
{
    for(int i=0; i<1000000L; ++i)
    {
        do_something(long_val);
    }
}


int main(int argc, char* argv[])
{
    std::vector<std::unique_ptr<std::thread>> threads;
    for(int i=0; i<100; ++i)
    {
        threads.push_back(std::move(std::unique_ptr<std::thread>(new std::thread(thread_func))));
    }
    for(int i=0; i<100; ++i)
    {
        threads[i]->join();
    }
    threads.clear();
    std::cout << long_val << std::endl;
    return 0;
}

为了编译它,我运行 g++ -std=c++11 main.cpp -lpthread -g 然后我得到名为 a.out 的可执行文件。

然后我运行 perf record --call-graph dwarf -- ./a.out 并等待 10 秒,然后我按 Ctrl+c 中断./a.out 因为它需要太多时间来执行。

最后,我运行 perf report -g graph --no-children,这是输出:

enter image description here

我的目标是找出代码的哪一部分最重。所以看起来这个输出可以告诉我 do_something 是最重的部分 (46.25%)。但是当我进入do_something时,我无法理解它是什么:std::_Bind_simplestd::thread::_Impl等。

那么如何从perf report的输出中得到更有用的信息呢?或者除了 do_something 是最重的事实之外我们不能得到更多?

最佳答案

在@Peter Cordes 的帮助下,我提出了这个答案。如果您有更多有用的信息,请随时提出您的答案。

You forgot to enable optimization at all when you compiled, so all the little functions that should normally inline away are actually getting called. Add -O3 or at least -O2 to your g++ command line. Optionally also profile-guided optimization if you really want gcc to do a good job on hot loops.

添加后-O3 , perf report 的输出变成:

enter image description here

现在我们可以从 futex_wake 得到一些有用的东西和 futex_wait_setup我们应该知道 mutex在 C++11 中由 futex 实现的Linux。所以结果是 mutex是这段代码中的热点。

关于c++ - 如何解读perf的报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57284544/

相关文章:

c++ - 如何使用线程安全函数将元素添加到数组?

c++ - 将 Variadic 模板包转换为 std::initializer_list

java - Profiler 选项卡未出现在 visualvm 中以进行远程 jmx 连接

c++ deque vs queue vs stack

c++ - 如何在一个 vs2008 项目中将库与 __stdcall 和 __cdecl 结合起来

c++ - WinRT c++ 中的 BitmapImage SetSourceAsync

python - 如何聚合热点(探查器)结果并在 kcachegrind 中查看

c++ - 初学者关于类型转换的问题

c++ - 判断一个抽象基类的构造函数是否为noexcept?

azure - 如何在消费模式下分析 .Net Core Azure Function?