`

在生产环境中使用php性能测试工具xhprof

    博客分类:
  • PHP
阅读更多

xhprof 是facebook开源出来的一个php性能测试工具,也可以称之为profile工具,这个词不知道怎么翻译才比较达意。跟之前一直使用的xdebug相比,有很多类似之处。以前对xdebug有一些记录还可以供参考 ,但是它的缺点是对性能影响太大,即便是开启了profiler_enable_trigger参数,用在生产环境中也是惨不忍睹,cpu立刻就飙到high。

而xhprof就显得很轻量,是否记录profile可以由程序控制,因此,用在生产环境中也就成为一种可能。在它的文档上可以看到这样一种用法:

以万分之一的几率启用xhprof,平时悄悄的不打枪。

PHP:
  1. if ( mt_rand ( 1 , 10000 ) == 1 ) {
  2.  xhprof_enable( XHPROF_FLAGS_MEMORY) ;
  3.  $xhprof_on = true ;
  4. }

在程序结尾处调用方法保存profile

PHP:
  1. if ( $xhprof_on ) {
  2.  // stop profiler
  3.  $xhprof_data = xhprof_disable( ) ;
  4.  
  5.  // save $xhprof_data somewhere (say a central DB)
  6.  ...
  7. }

也可以用register_shutdown_function方法指定在程序结束时保存xhprof信息,这样就免去了结尾处判断,给个改写的不完整例子:

PHP:
  1. if ( mt_rand ( 1 , 10000 ) == 1 ) {
  2.  xhprof_enable( XHPROF_FLAGS_MEMORY) ;
  3.  register_shutdown_function ( create_funcion( '' , "$xhprof_data = xhprof_disable(); save $xhprof_data;" ) ) ;
  4. }

至于日志,我暂时用的是最土的文件形式保存,定期清除即可。

BTW:xhprof生成的图形方式profile真是酷毙了,哪段代码成为瓶颈,一目了然。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics