Last active
May 8, 2020 06:40
-
-
Save bcremer/bbe63bbeba12e8334e913c6d633a38d7 to your computer and use it in GitHub Desktop.
Measure CPU Time / User / System Time in PHP Scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$measure = function (callable $lambda) { | |
$rUsage = getrusage(); | |
$startUTime = $rUsage['ru_utime.tv_usec'] + $rUsage['ru_utime.tv_sec'] * 1000000; | |
$startSTime = $rUsage['ru_stime.tv_usec'] + $rUsage['ru_stime.tv_sec'] * 1000000; | |
$startHrTime = hrtime(true); | |
$lambda(); | |
$total = (hrtime(true) - $startHrTime) / 1000000; | |
$rUsage = getrusage(); | |
$user = ($rUsage['ru_utime.tv_usec'] + $rUsage['ru_utime.tv_sec'] * 1000000 - $startUTime) / 1000; | |
$system = ($rUsage['ru_stime.tv_usec'] + $rUsage['ru_stime.tv_sec'] * 1000000 - $startSTime) / 1000; | |
$wait = $total - ($user + $system); | |
$measurements = [ | |
'user' => $user, | |
'system' => $system, | |
'wait' => $wait, | |
'total' => $total, | |
]; | |
$format = function (float $timeInMs) { | |
return str_pad(number_format($timeInMs, 0, ',', '.') . ' ms', 10, ' ', STR_PAD_LEFT); | |
}; | |
foreach ($measurements as $header => $value) { | |
echo "${header}:\t" . $format($value) . PHP_EOL; | |
} | |
echo PHP_EOL; | |
}; | |
echo "Factorial\n"; | |
$measure(function () { | |
(function ($_) { | |
$factorial = 1; | |
for ($i = 1; $i <= $_; $i++) { | |
$factorial = $factorial * $i; | |
} | |
return $factorial; | |
})(120000000); | |
}); | |
echo "usleep()\n"; | |
$measure(function () { | |
usleep(500000); | |
}); | |
echo "remote http call\n"; | |
$measure(function () { | |
file_get_contents('https://httpbin.org/delay/1'); | |
}); | |
echo "radom_bytes()\n"; | |
$measure(function () { | |
foreach (range(0, 100000) as $_) { | |
random_bytes(1024); | |
} | |
}); |
Author
bcremer
commented
Nov 18, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment