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

yipeiwu_com5年前PHP代码库
下面是使用示例:
复制代码 代码如下:

<?php
echo memory_get_usage(), '<br />'; // 313864
$tmp = str_repeat('http://www.nowamagic.net/', 4000);
echo memory_get_usage(), '<br />'; // 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;
}
}
}

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

<?php
//memory_get_usage();
$m1 = memory_get_usage();
echo '<br /> m1:',$m1;//58096
$a = 'hello';
$b = str_repeat($a,1000);
$m2 = memory_get_usage();
echo '<br /> m2:',$m2;//63424
unset($b);
$m3 = memory_get_usage();
echo '<br /> m3:',$m3;//58456
?>

相关文章

php获取客户端IP及URL的方法示例

本文实例讲述了php获取客户端IP及URL的方法。分享给大家供大家参考,具体如下: function getonlineip(){//获取用户ip if($_SERVER['HT...

PHP中break及continue两个流程控制指令区别分析

以下举例说明break 用来跳出目前执行的循环,并不再继续执行循环了。 复制代码 代码如下: <?php $i = 0; while ($i < 7) { if ($arr[...

PHP strtotime函数详解

先看手册介绍: strtotime — 将任何英文文本的日期时间描述解析为 Unix 时间戳 格式:int strtotime ( string $time [, int $now ]...

在PHP中使用redis

在Mac OS上安装redis首先是安装,它会默认安装到/usr/local/bin下复制代码 代码如下:cd /tmpwget http://redis.googlecode.com/...

windows下安装php的memcache模块的方法

windows下安装php的memcache模块的方法

要求必备知识 熟悉基本编程环境搭建。 运行环境 windows 7(64位); php-5.3; memcached-1.2.6 下载地址 环境下载 什么是PHP Memcache模块...