Home  >  Article  >  Backend Development  >  如何获知PHP程序占用多少内存(memory_get_usage)_php技巧

如何获知PHP程序占用多少内存(memory_get_usage)_php技巧

WBOY
WBOYOriginal
2016-05-17 09:08:57904browse

下面是使用示例:

复制代码 代码如下:

echo memory_get_usage(), '
'; // 313864
$tmp = str_repeat('http://www.nowamagic.net/', 4000);
echo memory_get_usage(), '
'; // 406048
unset($tmp);
echo memory_get_usage(); // 313952
?>

上面的程序后面的注释代表了它们的输出(单位为 byte(s)),也就是当时 PHP 脚本使用的内存(不含 memory_get_usage() 函数本身占用的内存)。

由上面的例子可以看出,要想减少内存的占用,可以使用 PHP unset() 函数把不再需要使用的变量删除。类似的还有:PHP mysql_free_result() 函数,可以清空不再需要的查询数据库得到的结果集,这样也能得到更多可用内存。

PHP memory_get_usage() 函数还可以有个参数,$real_usage,其值为布尔值。默认为 FALSE,表示得到的内存使用量不包括该函数(PHP 内存管理器)占用的内存;当设置为 TRUE 时,得到的内存为不包括该函数(PHP 内存管理器)占用的内存。

所以在实际编程中,可以用 memory_get_usage() 函数比较各个方法占用内存的高低,来选择使用哪种占用内存小的方法。

贴个使用函数:
复制代码 代码如下:

if (!function_exists('memory_get_usage'))
{
/**
+----------------------------------------------------------
* 取得内存使用情况
+----------------------------------------------------------
* @return integer
+----------------------------------------------------------
*/
function memory_get_usage()
{
$pid = getmypid();
if (IS_WIN)
{
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;
}
}
}

再来个函数使用例子:
复制代码 代码如下:

//memory_get_usage();
$m1 = memory_get_usage();
echo '
m1:',$m1;//58096
$a = 'hello';
$b = str_repeat($a,1000);
$m2 = memory_get_usage();
echo '
m2:',$m2;//63424
unset($b);
$m3 = memory_get_usage();
echo '
m3:',$m3;//58456
?>
Statement:
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