我们在实际编码中,要想实现对内存的查看和操作,许多程序员们第一个想到的就是PHP memory_get_usage()这个PHP脚本内存函数。
下面是PHP memory_get_usage()使用示例:
<?php
$size = memory_get_usage();
echo $size."bytes";
// output: 329568bytes
?>
实际使用中, 这样的显示并不友好, 更友好的显示如下:
<?php
function get_memory() {
$size = memory_get_usage();
$unit=array('B','KB','MB','GB','TB','PB');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
echo get_memory();
//output: 321.5 KB
?>
上面的程序后面的注释代表了它们的输出(单位为 byte(s)),也就是当时 PHP 脚本使用的内存(不含 memory_get_usage() 函数本身占用的内存)
由上面的例子可以看出,要想减少内存的占用,可以使用 PHP unset() 函数把不再需要使用的变量删除。类似的还有:PHP mysql_free_result() 函数,可以清空不再需要的查询数据库得到的结果集,这样也能得到更多可用内存。
PHP memory_get_usage()还可以有个参数,$real_usage,其值为布尔值。默认为 FALSE,表示得到的内存使用量不包括该函数(PHP 内存管理器)占用的内存;当设置为 TRUE 时,得到的内存为不包括该函数(PHP 内存管理器)占用的内存。
所以在实际编程中,可以用PHP memory_get_usage()比较各个方法占用内存的高低,来选择使用哪种占用内存小的方法。
注: memory_get_usage() 带有参数$real_usage.
Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.
如果查看内存实际占用, 应该使用memory_get_usage(true).
常用的检测:
用microtime函数就可以分析程序执行时间
memory_get_usage可以分析内存占用空间
SQL的效率可以使用打开慢查询查看日志分析
SQL 找到有瓶颈的使用EXPLAIN 来分析