To get the memory usage of php scripts in php, we can use php's own function memory_get_usage() as an example. It can check the memory occupied by the current PHP script execution. Let me take a look below.
memory_get_usage( )Official Grammar
1. Function prototype
int memory_get_usage ([ bool $real_usage = false ] )
Two, version compatible
PHP 4 >= 4.3.2, PHP 5
3. Basic usage and examples
We can directly use the PHP function memory_get_usage() to check how much memory the system has allocated to the current PHP script execution.
The code is as follows | Copy code | ||||
'; // 79248 $tmp = str_repeat('http://3aj.cn/', 4000); // 135408
echo memory_get_usage(), ' echo memory_get_usage(); // 79248 ?>
|
代码如下 | 复制代码 |
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)); ?> |
PHP memory_get_usage() function can also have a parameter, $real_usage, whose value is a Boolean value. The default is FALSE, which means that the obtained memory usage does not include the memory occupied by this function (PHP memory manager); when set to TRUE, the obtained memory does not include the memory occupied by this function (PHP memory manager).
代码如下 | 复制代码 |
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); ?> |
The code is as follows | Copy code |
<🎜> 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)); <🎜> <🎜> ?> |
The code is as follows | Copy code |
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);<🎜> ?> |
So in actual programming, you can use the memory_get_usage() function to compare the memory occupied by each method to choose which method takes up less memory.
Comes with a usage function:
The code is as follows
|
Copy code
|
||||
function memory_get_usage() {
$pid = getmypid();
exec('tasklist /FI "PID eq ' . $pid . '" /FO LIST', $output); |
exec("ps -eo%mem,rss,pid | grep $pid", $output);
}