php取得ターゲット関数実行時間例

2355 ワード

ターゲット関数の実行時間をテストするクラスを書きました.クラスの定義コードは次のとおりです.
 
  
/**
 * class EfficiencyTester
 * ,
 * @version 1.0 2013.04.13
 * @author Kross
 */
class EfficiencyTester {   
    /**
     * var $testTimes
     *
     */
    private $testTimes = 1000;

    /**
     * function getTime()
     * ,
     * @param $timeModel , :
     * @return int
     */
    private function getTime($timeModel = 'MS') {
        if ($timeModel == 'MS') {
            return microtime();
        } else if ($timeModel == 'S') {
            return time();
        } else {
            return microtime();
        }
    }
    /**
     * function testOnce()
     * ,
     * @param $functionName
     * @param $timeModel , :
     * @return double ( )
     */
    public function testOnce($functionName, $timeModel = 'MS') {       
        $startMicroTime = $this->getTime($timeModel);
        $functionName();
        $endMicroTime = $this->getTime($timeModel);

        $costMicroTime = $endMicroTime - $startMicroTime;

        return $costMicroTime;
    }
    /**
    * function test()
    * , ( )
    * @param $functionName
    * @param $timeModel , :
    * @return double
    */
    public function test($functionName, $timeModel = 'MS') {
        $totalMicroTimes = 0;
        for ($i = 1; $i <= $this->testTimes; $i++) {
            $totalMicroTimes += $this->testOnce($functionName);
        }
        return $totalMicroTimes / $this->testTimes;
    }
}
?>


クラスのテストコードは次のとおりです.
 
  
require_once('../class/EfficiencyTester.class.php');
$e = new EfficiencyTester();
echo $e->test('rand');
?>

最初はmicrotime()を直接使って時間を取得していましたが、単位が秒の実行時間を取得したい場合、書くのに多態ではないことを考慮してgettime()の関数を書いて異なる単位のタイムスタンプを取得しましたが、これで目標関数の実行時間が長くなったようです.gettime()関数の判断に時間がかかったためかもしれません.