How to get the real PHP memory usage on macOS

PHP provides the function memory_get_usage(), this is very helpful whenever you find your code using a lot of RAM. But this method has a significant limitation: it only counts memory used by your code directly and nothing out of the zend engine.

The problem is that you may use external libraries, a typical example is using libxml to parse any XML file. And you may want to know how much memory it uses. On linux it's pretty simple since you can parse the file /proc/{pid}/status but on macOS it's more complicated as this file does not exist.

And it looks like there is no easy solution. In my use case, as I wanted to monitor a single process, I decided to use top directly. So here is my solution:

$pid = getmypid();

echo exec("top -pid $pid -l 1 | grep $pid | awk '{print $8}'") . "\n";

Here are the details for what it does:

  • It runs top in log mode with only 1 iteration (-l 1) and only for your pid
  • It grep the line with your pid since top outputs a lot more
  • It finally get the 8th column using awk

This did the trick for me. It even shows human format for the memory size used. If you have any better/easiest/more reliable idea, feel free to comment!

Follow us on Twitter! https://twitter.com/swagdotind