Skip to content

Instantly share code, notes, and snippets.

@cameronjacobson
Created November 12, 2012 21:30
Show Gist options
  • Save cameronjacobson/4062036 to your computer and use it in GitHub Desktop.
Save cameronjacobson/4062036 to your computer and use it in GitHub Desktop.
simplified GC strategy for long-running / high volume
<?php
define('SCRIPT_MEMORY_CONSUMPTION', memory_get_usage(true));
gc_enable();
/**
* we might call gc_collect_cycles if
* memory_get_usage >= original memory * threshold
*/
define('MEMORY_THRESHOLD',2);
/**
* only if we're over memory threshold
* 5.05% probability we call GC manually
*/
define('GC_PROBABILITY', 5.05);
function collectGarbage() {
$fraction = number_format(GC_PROBABILITY/100, 4) * 10000;
$rand = mt_rand(1, 10000);
if($rand < $fraction){
if((SCRIPT_MEMORY_CONSUMPTION * MEMORY_THRESHOLD) <= memory_get_usage(true)){
gc_collect_cycles();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment