memory_get_usage () function returns the memory usage, memory_get_peak_usage () function returns the memory usage peaks, getrusage () returns CUP usage. But one thing Please note that you need to run on Linux in these functions.
Here we look at an example:
echo 'Starting memory:'.memory_get_usage(), '
';
$tmp = str_repeat('hello', 1000);
echo 'Memory after running:'.memory_get_usage(), '
';
unset($tmp);
echo 'Return to normal memory:'.memory_get_usage();
Output:
Starting memory:147256
Memory after running:155456
Return to normal memory:147256
In example, we use str_repeat () the string "hello" repeated 1000 times, eventually to compare the before and after consumption of memory size. As can be seen from the above example, in order to reduce memory usage, you can use the unset () function to no longer need to use a variable to delete. Similarly there mysql_free_result () function, when we no longer need to query result set data obtained can be used to release the memory occupied by the query.
Function memory_get_usage () can also have a parameter, $ real_usage, its value is a Boolean value. If set to TRUE, the acquisition of real memory allocated by the system size. If not set or set to FALSE, will be emalloc () reports the amount of memory used.
In the actual WEB development, you can compare the level of memory for each method to choose which method to use small memory PHP memory_get_usage ().
Function memory_get_usage () returns the number of bytes (in byte (s)). The following custom function to convert the number of bytes into MB easier to read:
function memory_usage() {
$memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
return $memory;
}
Common debugging PHP code performance detection methods are:
memory_get_usage can analyze memory footprint.
Microtime function can be analyzed using the program execution time.