Tracking Memory Usage in PHP

PHP is the de facto web programming language. It is also being used more and more in system application, no longer constricted to the web. As it becomes more complex, it uses more server resources such as CPU and memory. In system application and high traffic load, the memory usage becomes important. How can we track memory usage in PHP ?

There is a PHP function called memory_get_usage() that can be uesd. This function allows us, developers to take a peek into memory usage inside a script. Simply put a call at the top and a call at the bottom, then comparing the two, we will get an idea of how much memory is used inside the script.

A good explanation for memory allocation in the PHP engine :

real_usage works this way:

Zend’s memory manager does not use system malloc for every blocks it needs. Instead, it allocates big block of system memory (in increments of 256K, can be changed by setting environment variable ZEND_MM_SEG_SIZE) and manages it internally. So, there are two kinds of memory usage:

How much memory the engine took from the OS (“real usage”)
How much of this memory was actually used by the application (“internal usage”)
Which one of these is returned by memory_get_usage(). Which one is more useful for you depends on what you are looking into. If you’re looking into optimizing your in specific parts, “internal” might be more useful for you, if you tracking the usage globally, “real” would be of more use. memory_limit limits the “real” number, so as soon as all blocks that are permitted by the limit are taken from the system, and the memory manager can’t allocate requested block there the allocation fails. Note that “internal” usage in this case might be less than the limit, but the allocation still could fail because of the fragmentation.

Also, if you are using some external memory tracking tool, you can set environment variable USE_ZEND_ALLOC=0 which would disable the above mechanism and make the engine always use malloc(). This would have much worse performance but allows you to use malloc-tracking tools.

See also an article about this memory manager, it has some code examples too.

Source: Stack Overflow

The article referred to in the Stack Overflow discussion points to an IBM Developer Works coverage of the memory_get_usage() features. It also covers in depth about Memory Management. Definitely worth a read.