<?php

class Fiktiv_Performance
{
    /**
     * @var float
     */
    protected static $_start  = null;
    protected static $_result = null;

    /**
     * @return void
     */
    public static function begin()
    {
        self::$_start = microtime(true);
    }

    /**
     * @return float
     */
    public static function end()
    {
        self::$_result = microtime(true) - self::$_start;
        
        return self::result();
    }

    public static function result()
    {
        return self::$_result;
    }

    public static function benchmark($function, $params = array(), $iterations = 1000, $times = 10)
    {
        $result = array(
            'avg'      => null,
            'total'    => null,
            'max'      => null,
            'min'      => null,
            'results'  => array()
        );

        for($x=0; $x < $times; $x++) {

            self::begin();

            for($y=0; $y < $iterations; $y++) {
                call_user_func_array($function, $params);
            }

            $result['results'][] = self::end();
            
            $result['total'] += self::result();

            if ($result['min'] > self::result() || empty($result['min'])) {
                $result['min'] = self::result();
            }

            if ($result['max'] < self::result()) {
                $result['max'] = self::result();
            }
        }

        $result['avg'] = array_sum($result['results']) / count($result['results']);
        
        return $result;
    }
    
}
