Skip to content

Instantly share code, notes, and snippets.

@bcremer
Last active May 8, 2020 06:40
Show Gist options
  • Save bcremer/bbe63bbeba12e8334e913c6d633a38d7 to your computer and use it in GitHub Desktop.
Save bcremer/bbe63bbeba12e8334e913c6d633a38d7 to your computer and use it in GitHub Desktop.
Measure CPU Time / User / System Time in PHP Scripts
<?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);
}
});
@bcremer
Copy link
Author

bcremer commented Nov 18, 2019

$ php  measure_cpu_time.php
Factorial
user:	  1.335 ms
system:	      0 ms
wait:	      2 ms
total:	  1.337 ms

usleep()
user:	      0 ms
system:	      0 ms
wait:	    500 ms
total:	    500 ms

remote http call
user:	     22 ms
system:	     13 ms
wait:	  1.649 ms
total:	  1.684 ms

radom_bytes()
user:	     39 ms
system:	    550 ms
wait:	      1 ms
total:	    590 ms

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