PHP + MySQL 性能分析器

5
你知道vBulletin在调试模式下有一个SQL分析器吗?我该如何为自己的Web应用程序构建一个?它是使用过程化PHP构建的。
谢谢。
3个回答

8

http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html

上面的链接介绍了如何在查询之后获取所有SQL分析信息。

最好的实现方法是创建一个数据库类,并在其中添加一个“profile”标志来打开查询日志记录和适当的信息,如上面链接所示。

例如:

Class dbthing{
  var $profile = false;

  function __construct($profile = false){
    if($profile){
      $this->query('set profiling=1');
      $this->profile = true;
    }
    ...
  }

  function query($sql, $profile_this == false){
     ...
     if($this->profile && !$profile_this)
        $this->query("select sum(duration) as qtime from information_schema.profiling where query_id=1", true);
     ... // store the timing here
  }

}

3

我使用一个数据库连接包装器,可以在其周围放置一个性能分析包装器。这样,我可以丢弃包装器或更改它,而不需要更改我的基本连接器类。

class dbcon {
    function query( $q ) {}
}
class profiled_dbcon()
{
    private $dbcon;
    private $thresh;
    function __construct( dbcon $d, $thresh=false )
    {
        $this->dbcon = $d;
        $this->thresh = $thresh;
    }
    function queury( $q )
    { 
        $begin = microtime( true );
        $result = this->dbcon->query();
        $end = microtime( true );
        if( $this->thresh && ($end - $begin) >= $this->thresh ) error_log( ... );
        return $result;  
    }
}

使用10秒的阈值进行性能分析:

$dbc = new profiled_dbcon( new dbcon(), 10 );

我使用了error_log()函数来记录错误发生的时间。我不会将查询性能日志记录回数据库服务器,因为这会影响数据库服务器性能。你应该让你的Web服务器吸收这种影响。


1
这样做并不能得到准确的结果,因为microtime()提供的是服务器时间,而不是操作所需的实际处理器时间(或硬盘访问时间等)。最好使用mysql内置函数来获取进程所需的时间。 - Mike Valstar
1
@mike v:非常好的观点。感谢您发布有关MySQL分析器功能的链接,我很高兴能够了解更多相关信息。 - memnoch_proxy
1
你难道不是在给自己制造更多的工作吗?为什么不直接使用MySQL慢查询日志呢? - starmonkey
1
如果您正在针对一个普通的 MySQL 5.0 系统开发,并且没有将亚秒慢查询日志补丁添加到数据库的选项,那么这将成为您的下一个选择。 - memnoch_proxy

1
虽然有些晚,打开 PHP MyProfiler 可以帮助您实现此目标,并且您可以从代码中提取功能部分以供使用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接