自作の処理時間計測ツールの紹介
<?php
class StopWatch
{
private static $startTime;
private static $lastTime;
private static $total = 0;
private static $log = [];
public static function start($note = '')
{
$time = microtime(true);
self::$startTime = $time;
self::$lastTime = $time;
self::log(0, self::note($note));
}
public static function lap($note = '')
{
$time = microtime(true);
$lap = $time - self::$lastTime;
self::$lastTime = $time;
self::$total = $time - self::$startTime;
self::log($lap, self::note($note));
}
public static function stop($note = '')
{
$time = microtime(true);
$lap = $time - self::$lastTime;
self::$total = $time - self::$startTime;
self::log($lap, self::note($note));
}
/** @return array */
public static function getLog()
{
return self::$log;
}
private static function log($lap, $note)
{
self::$log[] = [
'total' => sprintf('%.6f', self::$total),
'lap' => sprintf('%.6f', $lap),
'note' => $note,
];
}
private static function note($note)
{
$dbg = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1];
if ($note !== '') {
$note .= ' ';
}
$note .= "{$dbg['file']}#{$dbg['line']}";
return $note;
}
}
使用例
<?php
StopWatch::start();
usleep(1000);
StopWatch::lap();
usleep(1000);
StopWatch::lap('コメントも書ける');
usleep(1000);
StopWatch::stop();
var_dump(StopWatch::getLog());
// 結果
// array(4) {
// [0]=>
// array(3) {
// ["total"]=>
// string(8) "0.000000"
// ["lap"]=>
// string(8) "0.000000"
// ["note"]=>
// string(21) "/workspace/Main.php#3"
// }
// [1]=>
// array(3) {
// ["total"]=>
// string(8) "0.001090"
// ["lap"]=>
// string(8) "0.001090"
// ["note"]=>
// string(21) "/workspace/Main.php#5"
// }
// [2]=>
// array(3) {
// ["total"]=>
// string(8) "0.002160"
// ["lap"]=>
// string(8) "0.001070"
// ["note"]=>
// string(46) "コメントも書ける /workspace/Main.php#7"
// }
// [3]=>
// array(3) {
// ["total"]=>
// string(8) "0.003232"
// ["lap"]=>
// string(8) "0.001072"
// ["note"]=>
// string(21) "/workspace/Main.php#9"
// }
// }