Heim  >  Artikel  >  Backend-Entwicklung  >  php获取目标函数执行时间

php获取目标函数执行时间

WBOY
WBOYOriginal
2016-07-25 08:54:051016Durchsuche
  1. /**
  2. * class EfficiencyTester
  3. * 效率测试器,测试函数的运行时间
  4. * @version 1.0 2013.04.13
  5. * @author Kross
  6. */
  7. class EfficiencyTester {
  8. /**
  9. * var $testTimes
  10. * 测试的次数
  11. */
  12. private $testTimes = 1000;
  13. /**
  14. * function getTime()
  15. * 根据时间模式,获取时间戳
  16. * @param $timeModel 时间模式,默认:微秒
  17. * @return int 时间戳
  18. */
  19. private function getTime($timeModel = 'MS') {
  20. if ($timeModel == 'MS') {
  21. return microtime();
  22. } else if ($timeModel == 'S') {
  23. return time();
  24. } else {
  25. return microtime();
  26. }
  27. }
  28. /**
  29. * function testOnce()
  30. * 测试目标函数一次,返回运行时间
  31. * @param $functionName 目标函数名
  32. * @param $timeModel 时间模式,默认:微秒
  33. * @return double 目标函数运行一次的时间(很随机)
  34. */
  35. public function testOnce($functionName, $timeModel = 'MS') {
  36. $startMicroTime = $this->getTime($timeModel);
  37. $functionName();
  38. $endMicroTime = $this->getTime($timeModel);
  39. $costMicroTime = $endMicroTime - $startMicroTime;
  40. return $costMicroTime;
  41. }
  42. /**
  43. * function test()
  44. * 测试目标函数多次,返回运行时间(平均值)
  45. * @param $functionName 目标函数名
  46. * @param $timeModel 时间模式,默认:微秒
  47. * @return double 目标函数运行的时间
  48. */
  49. public function test($functionName, $timeModel = 'MS') {
  50. $totalMicroTimes = 0;
  51. for ($i = 1; $i testTimes; $i++) {
  52. $totalMicroTimes += $this->testOnce($functionName);
  53. }
  54. return $totalMicroTimes / $this->testTimes;
  55. }
  56. }
  57. ?>
复制代码

测试代码:

  1. require_once('../class/EfficiencyTester.class.php');
  2. $e = new EfficiencyTester();
  3. echo $e->test('rand');
  4. ?>
复制代码

一开始直接使用 microtime() 获取时间的,后来考虑到如果想获得单位是秒的运行时间,这样写就不够多态了,然后就写了一个getTime() 的函数来获取不同单位的时间戳。 如此貌似目标函数的运行时间变长了,可能是因为 getTime() 函数中的判断占用了一部分时间。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn