Skip to content

Instantly share code, notes, and snippets.

@khoa-le
Last active October 8, 2024 07:36
Show Gist options
  • Save khoa-le/59771f1963a3a72e8ea9a72680a75d71 to your computer and use it in GitHub Desktop.
Save khoa-le/59771f1963a3a72e8ea9a72680a75d71 to your computer and use it in GitHub Desktop.
How to Measure Performance for PHP Function
<?php
function measurePerformance(callable $callback)
{
// Start measurement
$startTime = microtime(true);
$startMemory = memory_get_usage();
$startCpu = getrusage();
// Execute the block of code
$callback();
// End measurement
$endTime = microtime(true);
$endMemory = memory_get_usage();
$endCpu = getrusage();
// Calculate elapsed time, memory usage, and CPU times
$executionTime = $endTime - $startTime;
$memoryUsed = $endMemory - $startMemory;
$peakMemoryUsed = memory_get_peak_usage();
$userTimeUsed = ($endCpu["ru_utime.tv_sec"] * 1e6 + $endCpu["ru_utime.tv_usec"]) - ($startCpu["ru_utime.tv_sec"] * 1e6 + $startCpu["ru_utime.tv_usec"]);
$sysTimeUsed = ($endCpu["ru_stime.tv_sec"] * 1e6 + $endCpu["ru_stime.tv_usec"]) - ($startCpu["ru_stime.tv_sec"] * 1e6 + $startCpu["ru_stime.tv_usec"]);
// Output results
echo "Execution Time: " . $executionTime . " seconds</br>";
echo "Memory Usage: " . $memoryUsed/1024/1024 . " Mbytes</br>";
echo "Peak Memory Usage: " . $peakMemoryUsed/1024/1024 . " Mbytes</br>";
echo "User CPU Time: " . ($userTimeUsed / 1e6) . " seconds</br>";
echo "System CPU Time: " . ($sysTimeUsed / 1e6) . " seconds</br>";
}
// Example usage:
measurePerformance(function() {
return view('web.top');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment