function start_timer() { $this->start_time = $this->get_time(); }
function end_timer() { return ($this->get_time() - $this->start_time) ; } } $timer = new simple_profiler();
/****************************************** * Insert untimed initialization code here ******************************************/
$timer->start_timer(); /********************************* * Insert code for Method #1 here *********************************/ $old_time = $timer->end_timer();
$timer->start_timer(); /********************************* * Insert code for Method #2 here *********************************/ $new_time = $timer->end_timer();
echo "Method one took $old_time seconds.\n"; echo "Method two took $new_time seconds.\n\n";
if($old_time > $new_time) {
$percent = number_format(100 - (($new_time / $old_time) * 100), 2); echo "Method two was faster than Method one by $percent%<BR/>\n";
} else {
$percent = number_format(100 - (($old_time / $new_time) * 100), 2); echo "Method one was faster than Method two by $percent%<BR/>\n";
}
?>
In , I have defined a simple class suitable for most profiling needs, simple_profiler. Functionally, this profiler is nothing more than a fairly accurate clock that can be used to measure how long a particular segment of PHP code takes to execute. The remainder of this script serves as the template, which can be used to compare two different techniques used to accomplish the same task to determine the faster method.
In use, this template script has three segments to it that are of importance to us (identified by the comment placeholders). The first segment is the initialization segment, which provides a useful location by which to initialize portions of your script that you are not concerned with profiling. This segment is particularly useful to create dummy data (if profiling data processing), including files, and so on. The second and third segments serve as the placeholders for the actual code that is being profiled. There is no difference between the two segments, other than each should contain a different method of accomplishing the same task.
When this script is executed, it will record the amount of time taken to execute each of the two methods and then compare each to determine the faster method. To give us some sort of idea of exactly how much more efficient one method is to another, along with the execution times a percentage is also generated, showing the total improvement.
For the remainder of this section of the chapter I will not repeat the profiling code found in .