symfony2 - 获取执行时间

Sgo*_*kes 6 php profiling symfony

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

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

$starttime = microtime();
// do something
$duration = microtime() - $starttime;
Run Code Online (Sandbox Code Playgroud)

但由于显而易见的原因,我不能将它放在控制器中,因为整个引导程序都不会被跟踪.也不包括渲染模板.

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

Sgo*_*kes 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';
Run Code Online (Sandbox Code Playgroud)

我还注册了一个twig扩展,它使用全局并计算经过的时间:

<?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";
    }

}
Run Code Online (Sandbox Code Playgroud)

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

{{ performance_exectime() }}
Run Code Online (Sandbox Code Playgroud)

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