Home > php教程 > php手册 > 采用PHP函数memory_get_usage获取PHP内存清耗量的方法

采用PHP函数memory_get_usage获取PHP内存清耗量的方法

WBOY
Release: 2016-06-06 20:39:24
Original
1281 people have browsed it

PHP性能优化过程中需要获取PHP内存消耗,使用memory_get_usage()函数可获取当前的内存消耗情况,函数使用简单,这里讨论一下memory_get_usage()函数的用法与实例

一,函数原型
int memory_get_usage ([ bool $real_usage = false ] )

二,版本兼容
PHP 4 >= 4.3.2, PHP 5

三,基础用法与实例
1,获取当前的内存消耗量
代码如下:
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()输出
代码如下:
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,自定义函数获取数组或变量值大小
代码如下:
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);
?>

参考资料:
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template