Testing Memory Allocation

This nice routine is for testing PHP’s memory limits by increasingly allocating 50 more megabytes at a time. Each pass is setting the memory limit with an ini_set, then attempting to use just right up to that (10 megs under). It will run fairly fast until you start paging. You might want to turn the 6000 (6 gigs) to something that will fit on your server. The idea is to run this under the context where you’re having problems allocating memory with your PHP script and it should help you figure out how much memory you can use before your script breaks.


function tryMem($mbyte){
    $bytes = 1048576;
    echo("\tAllocate Attempt {$mbyte} MBs\n");
    $dummy = str_repeat("0", $bytes*$mbyte);
    echo("Current Memory Use: " . memory_get_usage(true)/$bytes . ' MBs');
    echo("\tPeak Memory Use: " . memory_get_peak_usage(true)/$bytes . ' MBs');
    $limit = $i.'M';
    ini_set('memory_limit', $limit); 
    echo("Memory limit set to: ". ini_get("memory_limit"));


Memory limit set to: 10M Allocate Attempt 0 MBs
Current Memory Use: 0.25 MBs Peak Memory Use: 0.25 MBs
Memory limit set to: 110M Allocate Attempt 100 MBs
Current Memory Use: 100.5 MBs Peak Memory Use: 100.5 MBs
Memory limit set to: 210M Allocate Attempt 200 MBs
Current Memory Use: 200.5 MBs Peak Memory Use: 200.5 MBs
Memory limit set to: 310M Allocate Attempt 300 MBs
Current Memory Use: 300.5 MBs Peak Memory Use: 300.5 MBs
Memory limit set to: 410M Allocate Attempt 400 MBs
Current Memory Use: 400.5 MBs Peak Memory Use: 400.5 MBs
Memory limit set to: 510M Allocate Attempt 500 MBs
Current Memory Use: 500.5 MBs Peak Memory Use: 500.5 MBs
Memory limit set to: 610M Allocate Attempt 600 MBs
Current Memory Use: 600.5 MBs Peak Memory Use: 600.5 MBs
Memory limit set to: 710M Allocate Attempt 700 MBs
Current Memory Use: 700.5 MBs Peak Memory Use: 700.5 MBs
Memory limit set to: 810M Allocate Attempt 800 MBs
Current Memory Use: 800.5 MBs Peak Memory Use: 800.5 MBs
Memory limit set to: 910M Allocate Attempt 900 MBs
Current Memory Use: 900.5 MBs Peak Memory Use: 900.5 MBs
Memory limit set to: 1010M Allocate Attempt 1000 MBs

Leave a Reply

Your email address will not be published. Required fields are marked *