php gets an example of the execution time of the target function

  • 2021-01-14 05:46:39
  • OfStack

A class is written to test the execution time of the target function. Here is the class definition code:


<?php
/**
 * class EfficiencyTester
 *  Efficiency tester that tests the elapsed time of a function 
 * @version 1.0 2013.04.13
 * @author Kross
 */
class EfficiencyTester {    
    /**
     * var $testTimes
     *  Number of tests  
     */
    private $testTimes = 1000;
    /**
     * function getTime()
     *  Gets a timestamp based on the time pattern 
     * @param $timeModel  Time mode, default: microsecond 
     * @return int  The time stamp 
     */
    private function getTime($timeModel = 'MS') {
        if ($timeModel == 'MS') {
            return microtime();
        } else if ($timeModel == 'S') {
            return time();
        } else {
            return microtime();
        }
    }
    /**
     * function testOnce()
     *  Test objective function 1 Times, returns the elapsed time 
     * @param $functionName  Target function name 
     * @param $timeModel  Time mode, default: microsecond 
     * @return double  Objective function operation 1 The second time (very random) 
     */
    public function testOnce($functionName, $timeModel = 'MS') {        
        $startMicroTime = $this->getTime($timeModel);
        $functionName();
        $endMicroTime = $this->getTime($timeModel);
        $costMicroTime = $endMicroTime - $startMicroTime;
        return $costMicroTime;
    }
    /**
    * function test()
    *  Test the target function multiple times and return the elapsed time (average) 
    * @param $functionName  Target function name 
    * @param $timeModel  Time mode, default: microsecond 
    * @return double  The time that the target function runs 
    */
    public function test($functionName, $timeModel = 'MS') {
        $totalMicroTimes = 0;
        for ($i = 1; $i <= $this->testTimes; $i++) {
            $totalMicroTimes += $this->testOnce($functionName);
        }
        return $totalMicroTimes / $this->testTimes;
    }
}
?>

Here is the test code for the class:


<?php
require_once('../class/EfficiencyTester.class.php');
$e = new EfficiencyTester();
echo $e->test('rand');
?>

1 started I was directly using microtime () for time, then consider if you want to get the operation of the unit is the second time, it was written not enough polymorphic, then I wrote a getTime () function to get the timestamp of the different units, but in this way, as the objective function of running time longer, perhaps because getTime () function in part 1 time.


Related articles: