Reputation: 41
I am trying to get REAL size (memory usage) of a variable in PHP. I know there is no straightforward method to achieve this but there is a simple "hack" using memory_get_usage().
<?php
function varSize()
{
$s = memory_get_usage();
$x = true;
echo memory_get_usage() - $s;
}
varSize();
echo '<br>';
$s = memory_get_usage();
$x = true;
echo memory_get_usage() - $s;
echo '<br>';
$s = memory_get_usage();
$x = unserialize(serialize(true));
echo memory_get_usage() - $s;
?>
This code returns 64, 160, 0 respectively. The hell why? The two first variants is an absolute copy-paste of each other! Why is this happens and how to get a real variable size?
Upvotes: 4
Views: 438
Reputation: 300
I found these functions in an internet search a while ago and use them in my scripts (sorry original author, lost the link to give you credit here). You could include the functions in your code to make things more modular and easier to read, then call the memoryusage function whenever you need it, eg...
// This function converts the number of bytes sent to it to kb, mb, gb, tb, pb as appropriate based on the size of memory (powers of 1024)
function convert($size)
{
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
// This function gets current PHP memory use and returns an approximate (rounded) figure back in: bytes, kb, mb, gb, tb, or pb as appropriate
function memoryusage() {
return convert(memory_get_usage(true));
}
....
// This is me wanting to know how much memory is being used at this point of the script
$memuse = memoryusage();
...
Upvotes: 1
Reputation: 2478
Use memory_get_usage(true) every time, you will get your answer.
If true is not passed , it returns memory used by emalloc. You can read more about that on Fucntion's Definition
Upvotes: 1