Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, how to check how much memory a certain loop is using

I'm currently making a PHP timer that checks how much time a certain way of doing something takes compared to another thing that accomplishes the same, basically benchmarking.

Now, I would also like to make this tool be able to tell how much memory that specific way of doing it is taking up.

So, for more info, I'm using microtime to check the start time, do 2000 thousand loops on that code and then do another microtime with some math to check how much time it took, so what I would like to do is, outside the microtime scope, also check for memory usage.

This is my current code:

// Set the amount of loops to do, default is 2000
$loops = 2000;
$start_time = microtime(true); // Start the timer

for($i = 0; $i < $loops; $i++) {
    // Code to test
}

$total_time = microtime(true) - $start_time; // Stop the timer, and figure out the total

ob_end_flush();   // Enable output again
echo $total_time; // Echo the timer's result
?>
like image 309
greduan Avatar asked Nov 18 '25 06:11

greduan


1 Answers

If you're on at least 5.2, memory_get_peak_usage() should work just fine.

http://php.net/manual/en/function.memory-get-peak-usage.php

You can call it once prior to the loop to get an idea of your baseline up to that point, then again afterward to see what peak was during loop execution.

Modifying your code...

// Set the amount of loops to do, default is 2000
$loops = 2000;
$base_mem = memory_get_peak_usage();
$start_time = microtime(true); // Start the timer

for($i = 0; $i < $loops; $i++) {
    // Code to test
}
$end_time = microtime(true);  // Stop the timer
$extra_mem = memory_get_peak_usage();

// figure out the totals
$total_time = $end_time - $start_time;
$total_mem = $extra_mem - $base_mem;

ob_end_flush();   // Enable output again
echo "Total Time: $total_time\n";
echo "Total Mem Above Basline: $total_mem bytes\n";
like image 168
FoolishSeth Avatar answered Nov 20 '25 19:11

FoolishSeth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!