To check memory usage, PHP provides an inbuilt function memory_get_usage(). This function returns the amount of memory allocated to a PHP script.
** memory_get_usage() function returns the amount of memory allocated to your PHP script in bytes.
To convert them in KB – memory_get_usage/1024
To convert them in MB – memory_get_usage/1048576
How to Check Memory Usage in PHP by memory_get_usage() Method
Let’s demonstrate this through an example.
Here is a simple PHP script, which creates an instance of MongoDB.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php /* Memory consumption before script execution */ echo "\n Memory Consumption is "; echo round(memory_get_usage()/1048576,2).''.' MB'; $connection = new Mongo(); $db = $connection->bookmarks; $collection = $db->emp; $obj = $collection->findOne(); var_dump($obj); /* Memory consumption */ echo "\n Memory Consumption is "; echo round(memory_get_usage()/1048576,2).''.' MB'; ?> |
It is very useful to know how much memory is allocated during your PHP script execution so that you can avoid Fatal Error: Allowed memory size exhausted.