Home  >  Article  >  Backend Development  >  PHP gets target function execution time

PHP gets target function execution time

WBOY
WBOYOriginal
2016-07-25 08:54:051070browse
  1. /**
  2. * class EfficiencyTester
  3. * Efficiency tester, test the running time of functions
  4. * @version 1.0 2013.04.13
  5. * @author Kross
  6. */
  7. class EfficiencyTester {
  8. /**
  9. * var $testTimes
  10. * Number of tests
  11. */
  12. private $testTimes = 1000;
  13. /**
  14. * function getTime()
  15. * Get the timestamp according to the time mode
  16. * @param $timeModel time mode, default: microseconds
  17. * @return int timestamp
  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. * Test the target function once and return the running time
  31. * @param $functionName Target function name
  32. * @param $timeModel Time mode, default: microseconds
  33. * @return double The time for the target function to run once ( Very random)
  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. * Test the target function multiple times and return the running time (average)
  45. * @param $functionName Target function name
  46. * @param $timeModel Time mode, default: microseconds
  47. * @return double Target function Running time
  48. */
  49. public function test($functionName, $timeModel = 'MS') {
  50. $totalMicroTimes = 0;
  51. for ($i = 1; $i <= $this->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() 函数中的判断占用了一部分时间。



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn