Timer.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Link : http://www.phpcorner.net
  4. * User : qingbing<780042175@qq.com>
  5. * Date : 2018-10-28
  6. * Version : 1.0
  7. */
  8. namespace Helper;
  9. class Timer
  10. {
  11. static private $_timeStore = []; // 时间记录栈
  12. /**
  13. * 开启一个 TIMER
  14. * @param string $type
  15. * @return string
  16. */
  17. static public function begin($type = 'app')
  18. {
  19. if (isset(self::$_timeStore[$type])) {
  20. return self::$_timeStore[$type];
  21. }
  22. return self::$_timeStore[$type] = self::microTime(false);
  23. }
  24. /**
  25. * 获取一个 TIMER 存活的时间
  26. * @param string $type
  27. * @return string
  28. * @throws Exception
  29. */
  30. static public function end($type = 'app')
  31. {
  32. if (!isset(self::$_timeStore[$type])) {
  33. throw new Exception(str_cover('没有"{type}"对应的 timer', [
  34. '{type}' => $type,
  35. ]));
  36. }
  37. $e = self::microTime(false);
  38. $s = self::$_timeStore[$type];
  39. unset(self::$_timeStore[$type]);
  40. return sprintf('%.6f', $e - $s);
  41. }
  42. /**
  43. * 获取当前的浮点型时间
  44. * @param bool $isFormat
  45. * @return string
  46. */
  47. static public function microTime($isFormat = true)
  48. {
  49. if ($isFormat) {
  50. list($microSec, $sec) = explode(" ", microtime());
  51. return Format::datetime($sec) . ' ' . substr($microSec, 2, 6);
  52. } else {
  53. return microtime(true);
  54. }
  55. }
  56. }