Skip to content

Instantly share code, notes, and snippets.

@joshdutcher
Last active October 23, 2015 14:32
Show Gist options
  • Save joshdutcher/de65b8f3fe6a2c8efd42 to your computer and use it in GitHub Desktop.
Save joshdutcher/de65b8f3fe6a2c8efd42 to your computer and use it in GitHub Desktop.
time_elapsed() - function to track php script execution time. To find where the code is slow.
function time_elapsed() {
$backtrace = debug_backtrace();
$calling_file = $backtrace[0]['file'];
$calling_line = $backtrace[0]['line'];
$call_string = $calling_file . ' line ' . $calling_line . '<br/>';
static $last = null;
$now = microtime(true);
if ($last == null) {
$outstring = $call_string . 'Starting timer...<br/>';
} else {
$elapsed = ($now - $last);
$outstring = $call_string . 'Elapsed: ' . round($elapsed, 4) . ' seconds';
}
echo $outstring;
$last = $now;
}
@joshdutcher
Copy link
Author

Use once to start the timer. Each use thereafter within the same script will output how long it took to get to it from the previous use. The $last variable resets to null at each new script execution.

Example use:

time_elapsed();
sleep(2);
time_elapsed();

will output

\calling_file.php line 3
Starting timer...
\calling_file.php line 5
Elapsed: 2.0009 seconds

Looks nicer if you replace echo with debug from my other gist, debug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment