I have a strange problem, I am running memory_get_usage functions in PHP. I run these after str_repeats. I would always expect the values from the memory usage to be more every time. But there are common occurances where its less each time. How is this even possible?
<?php
while(true) {
$num1 = rand(1,1000000);
$string1 = str_repeat(' ',$num1);
$memoryUsed1 = memory_get_peak_usage(false);
$memoryAllcoated1 = memory_get_peak_usage(true);
$memoryUsed2 = memory_get_usage(false);
$memoryAllcoated2 = memory_get_usage(true);
$num2 = rand(1,1000000);
$string2 = str_repeat(' ',$num2);
$memoryUsed3 = memory_get_peak_usage(false);
$memoryAllcoated3 = memory_get_peak_usage(true);
$memoryUsed4 = memory_get_usage(false);
$memoryAllcoated4 = memory_get_usage(true);
$num3 = rand(1,1000000);
$string3 = str_repeat(' ',$num3);
$memoryUsed5 = memory_get_peak_usage(false);
$memoryAllcoated5 = memory_get_peak_usage(true);
$memoryUsed6 = memory_get_usage(false);
$memoryAllcoated6 = memory_get_usage(true);
}
?>
$memoryUsed2 = 9200808
$memoryAllocated2 = 9961472
$memoryUsed4 = 7960528
$memoryAllocated4 = 8912896
$memoryUsed6 = 6230648
$memoryAllocated6 = 7077888
$num1 = 921888
$num2 = 465006
$num3 = 92134
So strings are repeating less. Is it measuring memory from the last point in the function? Can anyone solve this mystery?
ps. I am using a debugger to get these values, could this be unreliable?
There is no way the code inside your while
would produce three consecutively decreasing memory_get_usage
readings if run on its own. However, in a loop where each iteration overwrites the three variables with three values of random size, you can get a situation where they get smaller compared to previous pass, thus decreasing memory usage.
Consider this:
$multipliers = [
[10000000, 10000000, 10000000],
[1000, 1000, 1000],
];
foreach($multipliers as $numbers) {
foreach($numbers as $k=>$v) {
$s[$k] = str_repeat(" ", $v);
$m[$k] = memory_get_usage(true);
}
print_r($m);
}
and notice the results in the second pass:
Array
(
[0] => 10485760
[1] => 20709376
[2] => 30932992
)
Array
(
[0] => 20709376
[1] => 10485760
[2] => 262144
)