多线程开启gprof性能测试的简易方法

来源:互联网 发布:mac桌面文件复制到u盘 编辑:程序博客网 时间:2024/06/05 03:38

用到gprof时才知道,原来gprof只能对主线程统计耗时。manual上也没写线程相关的问题啊?

不过有现成的解决方案:http://sam.zoy.org/writings/programming/gprof.html

该方案封装了pthread_create(), 让线程初始化执行一个setitimer(ITIMER_PROF, ...)。

简易的方法是直接在代码中写个setitimer()。

#include <sys/time.h>#include <boost/thread.hpp>struct itimerval g_itimer;void foo(){    setitimer(ITIMER_PROF, &g_itimer, NULL);    for (int i = 0; i < 10000000; i++)        (void)i;}int main(){    getitimer(ITIMER_PROF, &g_itimer);    boost::thread t(&foo);    t.join();    return 0;}

g++ main.cpp -pg -lboost_thread

./a.out

gprof

这样就能统计出foo()的耗时了。没有setitimer()就不会有foo()的耗时统计。