Skip to content

Instantly share code, notes, and snippets.

@cbiggins
Created August 18, 2022 04:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cbiggins/ef55f71e43f29358e77a71c757770d45 to your computer and use it in GitHub Desktop.
Test for memory usage and bail out at a certain percent
function test_memory_limit() {
// Using drush but any arbitrary number for memory limit will do.
$mem_limit = drush_memory_limit();
$bail_percentage = 90;
$big_array = [];
$i = 9999;
while (TRUE) {
$i++;
// Just some string to make the array exponentially larger on each loop.
$big_array[] = str_repeat(uniqid() . uniqid(), $i);
// Memory check - 90% of total.
if (memory_get_usage(TRUE) >= ($bail_percentage/100*$mem_limit)) {
// Log errors or notify whoever that the process couldn't complete.
var_dump(memory_get_usage(TRUE));
echo 'This PHP script has been killed for using too much memory. An email has been sent.';
die();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment