Skip to content

Instantly share code, notes, and snippets.

@NickSdot
Last active June 25, 2023 08:17
Show Gist options
  • Save NickSdot/874b0640fbb2fac8d2accaf8b374d4af to your computer and use it in GitHub Desktop.
Save NickSdot/874b0640fbb2fac8d2accaf8b374d4af to your computer and use it in GitHub Desktop.
Debug memory usage in Laravel PHP

I wanted a simple way to debug memory usage in a Laravel or simple PHP project. Something I can just drop into my code without packages, extensions or what not. This little helper does what I need.

Setup

  1. Create a helpers.php (see below) where ever you want.
  2. Add the helper file to your composer.json in the autoload/files section.
"autoload": {
    "files": [
        "app/Support/helpers.php",
    ]
},

Usage

Use the function in any PHP file before and after the code you want to debug like so.

    \printMemory(); // before the script we want to check

    $someClass = new SomeClass();
    
    \printMemory(); // after we created our objects


    $someClass = null;
    unset($someClass);
                      
    \printMemory(); // after reset

The output will be something like this.

image

"autoload": {
"files": [
"app/Support/helpers.php", // use the correct path!
]
},
<?php
function printMemory($title = "", $unit = 'K'): void
{
$unitDivider = match($unit) {
'K' => 1024,
'M' => 1024 * 1024,
'G' => 1024 * 1024 * 1024,
};
// Current memory usage
$usage = round(memory_get_usage()/$unitDivider);
$usageAllocated = round(memory_get_usage(true)/$unitDivider);
// Peak memory usage
$peak = round(memory_get_peak_usage()/$unitDivider);
$peakAllocated = round(memory_get_peak_usage(true)/$unitDivider);
// Set to first caller
$backtrace = debug_backtrace()[1];
$location = sprintf(
'<a href="phpstorm://open?file=%1$s&line=%2$s">%3$s:%2$s</a><br>',
$backtrace['file'],
$backtrace['line'],
str_replace(base_path(), '', $backtrace['file']));
$output = "$title ";
$output .= '&nbsp;&nbsp;' . $location . '<br>';
$output .= '<strong>&nbsp;&nbsp;&nbsp;&nbsp;' . $usage . ' / ' . $usageAllocated . ' ' . $unit .
'</strong> (current)<br>';
$output .= '<strong>&nbsp;&nbsp;&nbsp;&nbsp;' . $peak . ' / ' . $peakAllocated . ' ' . $unit .
'</strong> (peak)<br>';
$output .= '<br>';
echo $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment