PHP stop function return from being overwritten -


i've created 2 functions:

function script_start_time() {     $start_time = microtime(true);     return $start_time; } 

and

function script_end_time() {   $start = script_start_time();     $end_time = microtime(true);     $time_taken = $end_time - $start;     $time_taken = round($time_taken, 4);     echo 'page generated in '.$time_taken.' seconds.'; } 

function script_start_time() called in header.php , function script_end_time called in footer.php

i trying use $start_time value in function script_end_time without resorting using global or static. 0 in echo, know incorrect.

where going wrong these functions seems $start getting overwritten in function script_end_time instead of retaining value function script_start_time.

the problem script_start_time function never saves value of $start_time , instead overwrites anytime function called. you're asking current time anytime call function.

if adjust code should work expected:

function script_start_time() {     // save value of $start_time first time requested     static $start_time;     if (empty($start_time))     {         $start_time = microtime(true);     }     return $start_time; }  function script_end_time() {        $start = script_start_time();     $end_time = microtime(true);     $time_taken = $end_time - $start;     $time_taken = round($time_taken, 4);     echo 'page generated in '.$time_taken.' seconds.'; }  script_start_time();  usleep(5000);  script_end_time(); // page generated in 0.0052 seconds. 

example: https://eval.in/861112


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -