一,函数原型
int memory_get_usage ([ bool $real_usage = false ] )
二,版本兼容
PHP 4 >= 4.3.2,PHP 5
三,基础用法与实例
1,获取当前的内存消耗量 代码如下:
PHP
echo memory_get_usage();
$var = str_repeat("liuhui",10000);
echo memory_get_usage();
unset($var);
echo memory_get_usage();
?>
echo memory_get_usage();
$var = str_repeat("liuhui",10000);
echo memory_get_usage();
unset($var);
echo memory_get_usage();
?>
分别输出:62328 122504 62416
说明:memory_get_usage()函数输出的数值为bytes单位 2,格式化memory_get_usage()输出
代码如下:
PHP
function convert($size){
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
echo convert(memory_get_usage(true));
?>
function convert($size){
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
echo convert(memory_get_usage(true));
?>
输出:256 kb 3,自定义函数获取数组或变量值大小
代码如下:
PHP
function array_size($arr) {
ob_start();
print_r($arr);
$mem = ob_get_contents();
ob_end_clean();
$mem = preg_replace("/\n +/","",$mem);
$mem = strlen($mem);
return $mem;
}
$memEstimate = array_size($GLOBALS);
?>
function array_size($arr) {
ob_start();
print_r($arr);
$mem = ob_get_contents();
ob_end_clean();
$mem = preg_replace("/\n +/","",$mem);
$mem = strlen($mem);
return $mem;
}
$memEstimate = array_size($GLOBALS);
?>
参考资料:http://cn.php.net/manual/en/function.memory-get-usage.php