phpmemorymicrotime

memory_get_usage() & microtime()


Good day! I have this code:

final class bench
{
    protected static $start_time;

    protected static $start_memory;

   public static function start()
   {
        self::$start_time   = microtime(true);
        self::$start_memory = memory_get_usage(true)/1024;
   }

   public static function finish()
   {
       echo PHP_EOL.'+'.round(memory_get_usage(true)/1024 - self::$start_memory, 3).' Kb load';
       echo PHP_EOL.'+'.round(microtime(true) - self::$start_time, 3).' Time.';
   }
}

But when I wanna use this little code here:

bench::start();

$array = ['f', 'g', 'f', 'd', 'ff'];

foreach($array as $key=>$value)
{
    echo $key.'f'.$value;
}

bench::finish();

I am getting bad results. It is saying me +0 Kb load +0 Time.

So I tried to use this example:

$start = memory_get_usage()/1024 . "\n";

for ($i = 1; $i <= 100; $i++) {
    echo $i;
}

echo '<br/>+'.round(memory_get_usage()/1024 - $start, 3).' Kb load';

And then I got normal results. Why so? Probably, there is something better than the code above


Solution

  • Your code is working. The memory used is a few bytes ; since round the division to 3 digits, 0kb is displayed.