Steven Matthews
Steven Matthews

Reputation: 11285

Getting the amount of memory used, both objectively and as a % of available

I would like to get the % of memory used by a program I am trying to run. It'll only be run on a Unix-based environment.

As far as I can tell, this should be real_usage() or memory_get_usage() in PHP, but I am unaware which is what I am supposed to use - there's little documentation and some documentation says that this is not possible.

I want to disallow a certain condition from executing once 75% of the available memory is used, or 125MB - whichever is first. How do I do this in PHP?  

Upvotes: 3

Views: 102

Answers (1)

Ray
Ray

Reputation: 41428

In your PHP script you can add the follow check to see if the process is about 125MB:

 if( round(memory_get_usage(true)/1048576) < 125) {
     //do your stuff here....
  }

This will only inform you on the memory used by the current PHP script.

For entire system memory and percentage in Linux, have php open the local file /proc/meminfo. It continually updates itself and the first 2 lines of the file have the current memory max and usage. You can use that to calculate the percentage for the whole system.

You can use good-old file() to read /proc/meminfo into an array, then parse the integers from the first 2 array members.

Good Luck!

Upvotes: 2

Related Questions