Created
August 18, 2022 04:45
-
-
Save cbiggins/ef55f71e43f29358e77a71c757770d45 to your computer and use it in GitHub Desktop.
Test for memory usage and bail out at a certain percent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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