PHP 內建 memory_get_usage() 返回當前腳本分配的記憶體(位元組),可用於比較不同實作的記憶體效率。
echo memory_get_usage() . "
"; // 313864 $tmp = str_repeat('https://www.example.com/', 4000); echo memory_get_usage() . "
"; // 406048 unset($tmp); echo memory_get_usage(); // 313952
釋放變數用 unset(),資料庫結果集用 mysql_free_result()。
$real_usagefalse(預設):不含 PHP 記憶體管理器本身開銷。true:含管理器開銷,反映系統實際分配。if (!function_exists('memory_get_usage')) {
function memory_get_usage() {
$pid = getmypid();
if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
exec('tasklist /FI "PID eq ' . $pid . '" /FO LIST', $output);
return preg_replace('/[^0-9]/', '', $output[5]) * 1024;
} else {
exec("ps -eo%mem,rss,pid | grep $pid", $output);
$output = explode(" ", $output[0]);
return $output[1] * 1024;
}
}
}
unset() 大型陣列、物件、資源。