dic
5
A simple PHP time testing unit
Published by Mic
I needed a simple way to check the timing behaviour of every section of my new php application.
There are some php testing unit out there, but I needed something more simpler and more usable.
So I’ve written our time testing unit, without using classes (I do like OO programming, but classes were unuseful for this simple target), in only one array and four functions.
Let’s see the code.
$ctk_timesteps=array(); function ctk_microtime_float() { list($usec, $sec) = explode(” “, microtime()); return ((float)$usec + (float)$sec); } function ctk_marktime($desc){ global $ctk_timesteps; $ctk_timesteps[$desc]=ctk_microtime_float(); } function ctk_start(){ ctk_marktime(’start’); } function ctk_report(){ ctk_marktime(‘final’); global $ctk_timesteps; $output=‘<div id="perftest" style="position:fixed;text-align:center; left:10px;top:10px;border:1px solid #b0b0b0;background-color:#e5efc9; padding:4px;z-index:100;color:#7b0000;"> <b>Time Analysis</b> (sec)<br/>’; $total_time=$ctk_timesteps[‘final’]-$ctk_timesteps[’start’]; $prevtime=$ctk_timesteps[’start’]; foreach ($ctk_timesteps as $step => $steptime){ if(($step!=’start’)&&($step!=‘final’)){ $difftime=$steptime-$prevtime; $perctime=$difftime*100/$total_time; $output.=$step.‘: ‘.number_format($difftime,8). ‘ (’.number_format($perctime,2).‘%)<br/>’; $prevtime=$steptime; } } $output.=‘Total time: ‘.number_format($total_time,8).‘</div>’; return $output; } //Start now! ctk_start();
To use this unit, simply copy the code in a file and include it at the very first line of the php script you want to profile and then get your analysis report in a string rendered by the ctk_report() function.
To print it on the page, put an echo ctk_report() at the end of your file, but inside the body of the returned html page.
The results we’ll be displayed in a fixed div at the top left margin of your browser window.
We use the array $ctk_timesteps to store all the times we want to track. You can add a new timestep, inside your code, with the ctk_marktime('stepname') function, using a string as the stepname (that is printed on the report).
The unit will calculate all the times between the steps (with also the precentage).


