金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks

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

(金庆的专栏)

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

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

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

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

  1. #include <sys/time.h>  
  2. #include <boost/thread.hpp>  
  3.   
  4. struct itimerval g_itimer;  
  5.   
  6. void foo()  
  7. {  
  8.     setitimer(ITIMER_PROF, &g_itimer, NULL);  
  9.     for (int i = 0; i < 10000000; i++)  
  10.         (void)i;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     getitimer(ITIMER_PROF, &g_itimer);  
  16.     boost::thread t(&foo);  
  17.     t.join();  
  18.     return 0;  
  19. }  

g++ main.cpp -pg -lboost_thread

./a.out

gprof

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


posted on 2012-08-01 16:23 金庆 阅读(1392) 评论(0)  编辑 收藏 引用 所属分类: 1. C/C++4. Linux/Unix

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理