Skip to content

Instantly share code, notes, and snippets.

@wilon
Created November 7, 2017 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilon/89b534696e1335052f8a7fe7c668597b to your computer and use it in GitHub Desktop.
Save wilon/89b534696e1335052f8a7fe7c668597b to your computer and use it in GitHub Desktop.
Count php script run time.
<?php
/**
* PHP time debug
* @param string $mark
* @param string $separate
* @return array
*/
function timeDebug($mark, $echo = true, $separate)
{
global $timeDebug;
$separate = $separate ?: (PHP_SAPI == 'cli' ? PHP_EOL : '<br>');
$mt = microtime();
if (!$mark) $mark = 'timeDebug';
$timeDebug[$mark][] = (float) (substr((string) $mt, 17) . substr((string) $mt, 1, 6));
$arr = $timeDebug[$mark];
$endKey = count($arr) - 1;
if (array_key_exists($endKey - 1, $arr)) {
$timeDiff = sprintf('%.5f', $arr[$endKey] - $arr[$endKey - 1]);
$separate = ' >> ' . $timeDiff . 's' . $separate;
$markDiff = $endKey . '_' . $endKey - 1;
$markDiffKey = $mark . '_diff';
$timeDebug[$markDiffKey][$markDiff] = $timeDiff;
}
if ($echo) {
echo $mark, ' ', date('Y-m-d H:i:s') . substr((string) microtime(), 1, 6), $separate;
}
return $timeDebug;
}
@wilon
Copy link
Author

wilon commented Nov 7, 2017

How to use?

<?php

timeDebug();

sleep(1);

timeDebug();

sleep(1);

timeDebug('forTime');

for ($i = 0; $i < 999999; $i++) {
    $a = count(['a', 'b', $i]);
}

timeDebug('forTime');

timeDebug();

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