如何在twig 中显示 执行时间


I created a new file performance.php in the web folder which looks like this:
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';
I also registered a twig extension which uses the global and calculates the elapsed time:
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";
    }
}
When we want to do some performance measurements, we can simply use performance.php. The template calls the function and can then display the execution time:
{{ performance_exectime() }}

评论

热门博文