memory_get_usage() returns the number of bytes used by the script when the function is called.
memory_get_peak_usage() returns the maximum amount of memory used by the entire script.
Note: If declared 1000 elements array and unset 100 elements, memory_get_peak_usage gives always maximum memory utilized by the script(always count the memory of 1000 elements). memory_get_usage gives what it is used when it gets called(if array is size 900 elements currently then it gives the memory of 900 elements).
For example
<?php
$array = array();
for ($i = 0; $i < 1000000; $i++)
{
$array[] = $i;
}
echo 'After building the array.<br>';
print_memory(); //Calling the function which find what would be the currently using memory and find for the entire script what would be maximum memory allocated.
unset($array); // Unset the array which means removed memory of 1000000 elements but this entire script maximum peak memory calculated with 1000000 elements and memory_get_usage gives after unsetting the array what would be the memory currently occupied.
echo 'After unsetting the array.<br>';
print_memory();
function print_memory()
{
/* Currently used memory */
$mem_usage = memory_get_usage();
/* Peak memory usage */
$mem_peak = memory_get_peak_usage();
echo 'The script is now using: <strong>' . round($mem_usage / 1024) . 'KB</strong> of memory.<br>';
echo 'Peak usage: <strong>' . round($mem_peak / 1024) . 'KB</strong> of memory.<br><br>';
}
Output is here
After building the array.
The script is now using: 33161KB of memory.
Peak usage: 33161KB of memory.
After unsetting the array.
The script is now using: 389KB of memory.
Peak usage: 33162KB of memory.