Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : PHP Options&Information : memory_get_usage

memory_get_usage

Returns the amount of memory allocated to PHP (PHP 4 >= 4.3.2, PHP 5)
int memory_get_usage ( [bool real_usage] )

Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

Parameters

real_usage

Set this to TRUE to get the real size of memory allocated from system. If not set or FALSE only the memory used by emalloc() is reported.

Return Values

Returns the memory amount in bytes.

ChangeLog

Version Description
5.2.1 Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 real_usage was added.

Examples

Example 1846. A memory_get_usage() example

<?php
// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo
memory_get_usage() . "\n"; // 57960

unset($a);

echo
memory_get_usage() . "\n"; // 36744

?>


Code Examples / Notes » memory_get_usage

magicaltux

When you need to get the OS, do not use $_SERVER['OS'] or $_ENV['OS'], better use PHP_OS constant !
<?php
if (substr(PHP_OS,0,3)=='WIN') {
 // [...]
}
?>
You also have other values such as CYGWIN_NT-5.0, Linux, ... this is the best way to get system's os (anyone on linux can do an "export OS=windows")


sandeepc

To get this in pre 4.2.3 do a (works on unix like systems only):
$my_pid = getmypid();
error_log("MEMORY USAGE (% KB PID ): ".`ps -eo%mem,rss,pid | grep $my_pid`);
found this tip somewhere in bugs.php.net!


e dot a dot schultz

This is a function that should work for both Windows XP/2003 and most distrabutions of UNIX and Mac OS X.
<?php
if( !function_exists('memory_get_usage') )
{
function memory_get_usage()
{
//If its Windows
//Tested on Win XP Pro SP2. Should work on Win 2003 Server too
//Doesn't work for 2000
//If you need it to work for 2000 look at http://us2.php.net/manual/en/function.memory-get-usage.php#54642
if ( substr(PHP_OS,0,3) == 'WIN')
{
      if ( substr( PHP_OS, 0, 3 ) == 'WIN' )
               {
              $output = array();
              exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );
       
              return preg_replace( '/[\D]/', '', $output[5] ) * 1024;
               }
}else
{
//We now assume the OS is UNIX
//Tested on Mac OS X 10.4.6 and Linux Red Hat Enterprise 4
//This should work on most UNIX systems
$pid = getmypid();
exec("ps -eo%mem,rss,pid | grep $pid", $output);
$output = explode("  ", $output[0]);
//rss is given in 1024 byte units
return $output[1] * 1024;
}
}
}
?>


guenter_doege

The Win XP / 2003 workaround script will also work with windows 2000 with a few slight modifications.
Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html because win/2000 itself does not provide a task list utility.
<?php
function getMemUsage()
{
   
      if (function_exists('memory_get_usage'))
      {
          return memory_get_usage();
      }
      else if ( substr(PHP_OS,0,3) == 'WIN')
      {
          // Windows 2000 workaround
          $output = array();
          exec('pslist ' . getmypid() , $output);
          return trim(substr($output[8],38,10));
      }
      else
      {
          return '<b style="color: red;">no value</b>';
      }
}
?>


joe

the various memory_get_usage replacements here don't seem to work on Mac OS X 10.4(Intel)
I got it to work like this...
function memory_get_usage()
{
    $pid = getmypid();
    exec("ps -o rss -p $pid", $output);
    return $output[1] *1024;
}


ad-rotator.com

The method sandeepc at myrealbox dot com posted yields larger memory usage, my guess is that it includes all the PHP interpreter/internal code and not just the script being run.
1) Use ps command
MEMORY USAGE (% KB PID ):  0.8 12588 25087 -> about 12MB
2) Use memory_get_usage()
int(6041952) -> about 6MB


php_dev

Regarding the function posted by
e dot a dot schultz at gmail dot com
I am running XAMPP on a windows box and the memory usage that the function is giving me is for the entire instance of apache.exe. Thats a lot more memory than my single PHP process. Maybe this works as expected on IIS, but not on apache!  (I am getting a report of about 26MB on win vs. only 700k on Linux).


john ring

Oops, that was a question.
I'll change it to a note simply:
Note: This is NOT enabled at all in the Win32 builds.
Best regards


grey - greywyvern - com

If nothing else in the user notes below works for you, you can get a very (VERY) rough estimate of PHP memory usage by outputting the $GLOBALS array, stripping it of indentation whitespace, and counting the characters in the resulting string.  This method has a very high overhead (to be expected), but works on all operating systems, regardless of whether or not they have the --enable-memory-limit config option set.  I find that the syntax overhead of the print_r() statement roughly accounts for the PHP runtime base memory usage.
The code below is set up to work on all arrays, not just the $GLOBALS array.  Keep in mind that outside data referenced by resource IDs, such as database results and open file data, is not included in this total.
<?php
function array_size($arr) {
 ob_start();
 print_r($arr);
 $mem = ob_get_contents();
 ob_end_clean();
 $mem = preg_replace("/\n +/", "", $mem);
 $mem = strlen($mem);
 return $mem;
}
$memEstimate = array_size($GLOBALS);
?>
Use only if being off to either side by at least 20% is acceptible for your purposes.


randolphothegreat

I'd just like to point out that although sandeepc at myrealbox dot com's idea for displaying the current memory usage is a good one, it's perhaps a bad idea to pipe the entire process list through grep. A better performing method would be to select only the process we're interested in:
<?
$pid = getmypid();
error_log('MEMORY USAGE (% KB PID ): ' . `ps --pid $pid --no-headers -o%mem,rss,pid`);
?>
True, it's not much of a performance boost, but every bit helps.


vesa dot kivisto

I was unable to get the previous examples working properly and created code which works at least for me. Enjoy!
// Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html
// This is because win/2000 itself does not provide a task list utility.
//
function getMemoryUsage() {
// try to use PHP build in function
if( function_exists('memory_get_usage') ) {
 return memory_get_usage();
}
// Try to get Windows memory usage via pslist command
if ( substr(PHP_OS,0,3) == 'WIN') {
 
 $resultRow = 8;
 $resultRowItemStartPosition = 34;
 $resultRowItemLength = 8;
 
 $output = array();
 exec('pslist -m ' . getmypid() , $output);
   
 return trim(substr($output[$resultRow], $resultRowItemStartPosition, $resultRowItemLength)) . ' KB';
 
}

// No memory functionality available at all
return '<b style="color: red;">no value</b>';
 
}


webnospamsjwans

A quick and dirty Windows XP / 2003 wordaround:
<?php
function getMemUsage()
{

if (function_exists('memory_get_usage'))
{
return memory_get_usage();
}
else if ( strpos( strtolower($_SERVER["OS"]), 'windows') !== false)
{
// Windows workaround
$output = array();

exec('tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output);
return substr($output[5], strpos($output[5], ':') + 1);
}
else
{
return '<b style="color: red;">no value</b>';
}
}
?>


xolox

<?php
// Original from http://php.net/memory_get_usage by websjwans at hotmail dot com. Thanks alot!
if ( ! function_exists( 'memory_get_usage' ) ):
// Only define function if it doesn't exist
function memory_get_usage()
{
// If we are running on Windows
if ( substr( PHP_OS, 0, 3 ) == 'WIN' ):
$output = array();
// Should check whether tasklist is available, but I'm lazy
exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );
// Filter non-numeric characters from output. Why not use substr & strpos?
// I'm running Windows XP Pro Dutch, and it's output does not match the
// English variant, as will all other translations. This is a more generic
// approach, and has a better chance of actually working
return preg_replace( '/[^0-9]/', '', $output[5] ) * 1024;
// Tasklist outputs memory usage in kilobytes, memory_get_usage in bytes.
// So we multiply by 1024 and in the process convert from string to integer.
else:
return false;
endif;
}
endif;
?>
Works for me. Functionality should match memory_get_usage(), albeit slower (exec & regex). Have fun!
- Peter Odding


Change Language


Follow Navioo On Twitter
assert_options
assert
dl
extension_loaded
get_cfg_var
get_current_user
get_defined_constants
get_extension_funcs
get_include_path
get_included_files
get_loaded_extensions
get_magic_quotes_gpc
get_magic_quotes_runtime
get_required_files
getenv
getlastmod
getmygid
getmyinode
getmypid
getmyuid
getopt
getrusage
ini_alter
ini_get_all
ini_get
ini_restore
ini_set
main
memory_get_peak_usage
memory_get_usage
php_ini_scanned_files
php_logo_guid
php_sapi_name
php_uname
phpcredits
phpinfo
phpversion
putenv
restore_include_path
set_include_path
set_magic_quotes_runtime
set_time_limit
sys_get_temp_dir
version_compare
zend_logo_guid
zend_thread_id
zend_version
eXTReMe Tracker