The PHP built-in function memory_get_usage () returns the amount of memory currently allocated to the PHP script in bytes (byte). In the actual development of the web, these functions are very useful, and we can use it to debug PHP code performance.
The Memory_get_usage () function returns memory usage, the Memory_get_peak_usage () function returns the peak memory usage, and getrusage () returns the cup usage. But one thing to note is that these functions need to run on Linux.
Let's take a look at an example:
Copy Code code as follows:
Echo ' Start memory: '. Memory_get_usage (), ';
$tmp = str_repeat (' Hello ', 1000);
Echo ' After running memory: '. Memory_get_usage (), ';
Unset ($TMP);
Echo ' Back to normal memory: '. Memory_get_usage ();
Output results:
Copy Code code as follows:
Start Memory: 147296
Memory after running: 152456
Back to normal memory: 147296
In the example, we use Str_repeat () to repeat the string "Hello" 1000 times, and finally to compare the memory consumption before and after. As you can see from the above example, to reduce memory footprint, you can use the unset () function to remove variables that you no longer need to use. Similar to the Mysql_free_result () function, you can use the memory used to release the query when we no longer need to query the resulting set of data.
The function memory_get_usage () can also have a parameter, $real _usage, whose value is a Boolean value. If set to true, gets the real memory size allocated by the system. If not set or set to FALSE, the amount of memory used is reported by Emalloc ().
In the actual web development, you can use the PHP memory_get_usage () to compare each method to occupy the level of memory, to choose the use of the memory of the small method.
The number of bytes that the function Memory_get_usage () returns (in Byte (s)). The following custom function converts the number of bytes to MB easier to read:
Copy Code code as follows:
function Memory_usage () {
$memory = (! function_exists (' memory_get_usage '))? ' 0 ': Round (Memory_get_usage ()/1024/1024, 2). ' MB ';
return $memory;
}
Common debugging methods to detect the performance of PHP code are:
Memory_get_usage can analyze memory footprint.
You can use the Microtime function to analyze program execution time.
The above is to use Memory_get_usage to get the full content of the memory of PHP code, this function is very efficient, the need for small partners can refer to the following