复制代码
上面的程序后面的注释代表了它们的输出(单位为 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;}}}
复制代码
再来个使用函数的例子:
复制代码
