Tracking Memory Usage in PHP

real_usage works this way:

Zend’s memory manager does not use system malloc for every block it needs. Instead, it allocates a 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:

  1. How much memory the engine took from the OS (“real usage”)
  2. How much of this memory was actually used by the application (“internal usage”)

Either one of these can be 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 code in specific parts, “internal” might be more useful for you. If you’re tracking memory 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 a 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 fragmentation.

Also, if you are using some external memory tracking tool, you can set this
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.

Leave a Comment