2012-04-18 93 views
5

我想为我的应用程序使用symfony2创建一个状态页面,我希望打印特定请求的执行时间(以及其他数据)。无论如何我都找不到这样做。symfony2 - 获得执行时间

我知道我可以跟踪与代码部分的执行时间:

$starttime = microtime(); 
// do something 
$duration = microtime() - $starttime; 

但显而易见的原因,我不能把它放在控制器,为整个引导将无法跟踪。也不包括渲染模板。

有没有办法尽可能地接近脚本的总执行时间?

+0

内置的分析系统如何?它将在2.1中拥有更多精彩的功能,比如详细的时间图,有点类似于萤火虫和webkit的图表。 – gilden 2012-04-18 15:46:51

+0

我想在一个特殊页面上的生产环境中执行此操作。现在我不知道剖析器如何工作。当我服务一项行动并且对所有其他行为没有表现影响时,我能否以某种方式“激活”它? – Sgoettschkes 2012-04-18 19:04:58

+0

对于在生产服务器上进行分析,您可能需要查看xhprof ... – greg0ire 2012-04-18 21:41:36

回答

8

我发现了一种我认为适合我们的用例的方法。我创建的Web文件夹的新文件performance.php它看起来像这样:

<?php 
/** 
* This file is only used for doing realtime performance measurement 
* Right now only the microtime is calculated, but in the future the 
* xhproof module could be used: http://de2.php.net/manual/en/book.xhprof.php 
* 
* MAKE SURE TO NOT USE THIS FILE IN PRODUCTION FOR OTHER STUFF THAN REAL TIME 
* PERFORMANCE MEASUREMENT 
*/ 

$GLOBALS['PerformanceTwigExtensionMicrotime'] = microtime(true); 

require_once __DIR__.'/app.php'; 

我也注册了,它使用全球和计算所经过的时间树枝延伸:

<?php 

namespace Acme\DemoBundle\Extension; 

class PerformanceTwigExtension extends \Twig_Extension { 

    public function getFunctions() { 
     return array(
      'performance_exectime' => new \Twig_Function_Method($this, 'getExecTime') 
     ); 
    } 

    public function getExecTime() { 
     if (!isset($GLOBALS['PerformanceTwigExtensionMicrotime'])) { 
      return 0; 
     } 

     $durationInMilliseconds = (microtime(true) - $GLOBALS['PerformanceTwigExtensionMicrotime']) * 1000; 
     return number_format($durationInMilliseconds, 3, '.', ''); 
    } 

    public function getName() { 
     return "performance_extension"; 
    } 

} 

当我们想做一些性能测量,我们可以简单地使用performance.php。模板调用的函数,然后可以显示执行时间:

{{ performance_exectime() }} 

它输出0,如果开始时间没有设置(例如,当使用正常app.php),所以它的安全在任何情况下使用。另一方面,如果有人决定使用performance.php作为入口点,它不应该破坏任何东西,因为只有一个全局变量是不同的。

+0

这是一个好主意! (考虑将其转化为wiki条目。) – 2013-09-20 23:54:59

1

由于PHP 5.4,我们可以做microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']

如何Symfony2的使用:

src/AppBundle/Twig/AppExtension.php

<?php 

namespace AppBundle\Twig; 

class AppExtension extends \Twig_Extension 
{ 
    public function getFunctions() 
    { 
     return [ 
      new \Twig_SimpleFunction('request_time', [$this, 'requestTime'], ['is_safe' => ['html']]), 
     ]; 
    } 

    public function requestTime($decimals = 3) 
    { 
     return number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], $decimals); 
    } 

    public function getName() 
    { 
     return 'app_extension'; 
    } 
} 

鉴于:

<footer class="footer"> 
    <div class="container"> 
     <p class="text-muted">{{ request_time() }}s</p> 
    </div> 
</footer> 

app/config/services.yml

services: 
    app.twig_extension: 
     class: AppBundle\Twig\AppExtension 
     public: false 
     tags: 
      - { name: twig.extension }