duanji1924 2016-06-09 20:58
浏览 142
已采纳

显示ZF2请求执行时间

I want to print in every page of my site, which is in ZF2, the request execution time.

I have already defined a constant within the index.php (which is the first file the request access) with the request initial microtime(true).
Now, where should I get the request final microtime(true)?

My plan is to have something like this:

$executionTime = ($finalTime - $initialTime) / 1000000; // in seconds
$executionTime = number_format($executionTime, 2);
  • 写回答

5条回答 默认 最新

  • doushen9863 2016-06-13 15:04
    关注

    My solution is based on this answer.

    Every view of mine has a footer.phtml attached to it, so if I print it there, there will be no need to change many files.

    To print the time there, first I wrote something specific to that footer.phtml, for example Execution time:

    Than in module/Application/Module.php I added this code to onBootstrap()

    $eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_FINISH, function($e) {
        $time = microtime(true) - REQUEST_MICROTIME;
    
        // formatting time to be more friendly
        if ($time <= 60) {
            $timeF = number_format($time, 2, ',', '.').'s'; // conversion to seconds
    
        } else {
            $resto  = fmod($time, 60);
            $minuto = number_format($time / 60, 0);
            $timeF = sprintf('%dm%02ds', $minuto, $resto); // conversion to minutes and seconds
        }
    
        // Search static content and replace for execution time
        $response = $e->getResponse();
        $response->setContent(str_replace(
            'Execution time:', 'Execution time: '.$timeF, $response->getContent()));
    
    }, 100000);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?