First , you need add this in app_dev.php, at the begining.
$GLOBALS['PerformanceTwigExtensionMicrotime'] = microtime(true);in php, we need to create a twig extension service:
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"; } }And another normal service for controller:
class Performance { private $execTimeArray; public function __construct(){ $this->execTimeArray=array(); } 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"; } public function addTime($label=null){ if (null==$label) $this->execTimeArray[]=$this->getExecTime(); else $this->execTimeArray[$label]=$this->getExecTime(); } public function getTimes(){ return $this->execTimeArray; } }and then we can use this in controller;
$perf=$this->get('acme.performance'); $perf->addTime('get in controller');the addTime can be used in all the controller. After this ,we can show the performance in a twig template:
{% for key, time in times %}{{ key }} : {{ time }}{% endfor %} {{ performance_exectime() }}
评论
发表评论