May 22nd 2007
PHP Timing Script With Average Time
I needed a script that would time some php I wrote to see if using an output buffer would speed it up. I used the php microtime() function to accomplish the timing feature, and combined that with sessions to capture an average execution time. This is the result:
<?php
session_start();
if (isset($_GET['clear'])) session_unset();
else {
$ac = $_SESSION['avg_count']++;
}
$ts = microtime(true);
ob_start(); // this starts to buffer the output, comment this line to test speed with out it.
?>
[[PHP code to test here]]
<?php
ob_end_flush(); // this function flushes the buffer. Comment this line to test without it.
$ts = round(microtime(true)-$ts,3);
$_SESSION['exe_avg'][] = $ts;
$ea = @round(array_sum($_SESSION['exe_avg'])/$_SESSION['avg_count'],4);
print “<p>Page executed in <strong>{$ts}s</strong><br>”;
print “Average execution time: <strong>{$ea}s</strong> ({$_SESSION['avg_count']} attempts)<br>”;
print “<a href=’?clear=1′>Clear Session</a></p>”
?>
As a general rule, using the output buffer can greatly increase the execution speed of php programs.
