Skip to content

Instantly share code, notes, and snippets.

@radicaldingos
Last active October 28, 2015 15:28
Show Gist options
  • Save radicaldingos/c5c22dabea3decf6a235 to your computer and use it in GitHub Desktop.
Save radicaldingos/c5c22dabea3decf6a235 to your computer and use it in GitHub Desktop.
Function to determine the memory footprint of a PHP variable or object
<?php
/**
* Conversion d'un nombre d'octets en une taille lisible
*
* @param int $size Taille en octets
*
* @return string Taille lisible
*/
function convertSize($size)
{
$unite = array('o', 'Kio', 'Mio', 'Gio', 'Tio');
return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unite[$i];
}
/**
* Détermination de la taille d'une variable
*
* On mesure l'occupation mémoire, puis on réalise une copie de la variable
* en mémoire, et on remesure l'occupation mémoire. On en déduit alors la taille
* de la variable.
*
* @param mixed $var Variable à mesurer
* @param boolean $convert TRUE pour convertir, FALSE pour une taille en octets
*
* @return string|int Taille de la variable
*/
function varSize($var, $convert = true)
{
$start_memory = memory_get_usage();
$temp = unserialize(serialize($var));
$taille = memory_get_usage() - $start_memory;
if ($convert) {
return convertSize($taille);
} else {
return $taille;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment