Symfony2 - Get Runtime

I want to make a status page for my application using symfony2 where I want to print the runtime (along with other data) of a specific request. I could not do it.

I know that I can track the execution time of a piece of code with:

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

But for the obvious reason, I cannot put it in the controller, since the entire bootstrap will not be tracked. Also, the template display will not be enabled.

Is there a way to get closer to the overall runtime of the script?

+5
source share
2 answers

I found a way that I think is appropriate for our use case. I created a new performance.php file in a web folder that 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';

, :

<?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 , , .

+8

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 }
+1

All Articles