2012-04-18 94 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 }