Skip to content

Instantly share code, notes, and snippets.

@karelbemelmans
Last active December 18, 2015 14:09
Show Gist options
  • Save karelbemelmans/5795324 to your computer and use it in GitHub Desktop.
Save karelbemelmans/5795324 to your computer and use it in GitHub Desktop.
Memory and time usage for PHP function
<?php
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
function formatTime($seconds) {
$seconds = max(1, (int)$seconds);
if ($seconds > 60) {
$minutes = (int)($seconds / 60);
$seconds = $seconds % 60;
return "$minutes mins, $seconds seconds";
}
return $seconds . ' seconds';
}
// start loggedin memory and time
$time_start = microtime_float();
$global_memory_start = memory_get_usage();
// *Magic happens here*
// Show timing end
$time_end = microtime_float();
$memory_end = memory_get_usage();
$runtime = formatTime($time_end - $time_start);
$memory_used = formatBytes($memory_end - $global_memory_start, 3);
print "# Finished in: $runtime\n";
print "# Memory used: $memory_used\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment