The built-in function memory_get_usage() of PHP can return the amount of memory currently allocated to the PHP script, in bytes. In actual WEB development, these functions are very useful and we can use it to debug PHP code performance.
The memory_get_usage() function returns the memory usage, the memory_get_peak_usage() function returns the memory usage peak, and getusage() returns the CUP usage. But one thing to note is that these functions need to be run on Linux.
Let's take a look at an example:
echo 'Start memory:'.memory_get_usage(), ''; $tmp = str_repeat('hello', 1000); echo 'Operation memory:'.memory_get_usage(), ''; unset($tmp); echo 'Back to normal memory:'.memory_get_usage();
Output result:
Start Memory: 147296
After running memory: 152456
Back to normal memory: 147296
In the example, we used str_repeat() to repeat the string "hello" 1000 times, and finally compare the memory consumed before and after. As can be seen from the above example, in order to reduce memory usage, you can use the unset() function to delete variables that you no longer need to use. There is also the mysql_free_result() function. When we no longer need to query the result set obtained by the data, we can use the memory occupied by the free query.
The function memory_get_usage() can also have a parameter, $real_usage, whose value is a Boolean value. If set to TRUE, gets the true memory size allocated by the system. If not set or set to FALSE, the amount of memory used by email() reports.
In actual WEB development, PHP memory_get_usage() can be used to compare the memory occupancy of each method to choose which method to use to occupy less memory.
The number of bytes returned by the function memory_get_usage() (unit is byte(s)).
The following custom function converts 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; }
Commonly used methods for debugging and detecting PHP code performance are:
memory_get_usage can analyze memory footprint.
Use the microtime function to analyze the program execution time.
Through this article, you know how php obtains memory usage. I hope this article can be helpful to everyone's learning.