Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Timer.php 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. /**
  11. *
  12. */
  13. class Timer
  14. {
  15. private $timerStart;
  16. private $memoryStart;
  17. /**
  18. * @return \Piwik\Timer
  19. */
  20. public function __construct()
  21. {
  22. $this->init();
  23. }
  24. /**
  25. * @return void
  26. */
  27. public function init()
  28. {
  29. $this->timerStart = $this->getMicrotime();
  30. $this->memoryStart = $this->getMemoryUsage();
  31. }
  32. /**
  33. * @param int $decimals
  34. * @return string
  35. */
  36. public function getTime($decimals = 3)
  37. {
  38. return number_format($this->getMicrotime() - $this->timerStart, $decimals, '.', '');
  39. }
  40. /**
  41. * @param int $decimals
  42. * @return string
  43. */
  44. public function getTimeMs($decimals = 3)
  45. {
  46. return number_format(1000 * ($this->getMicrotime() - $this->timerStart), $decimals, '.', '');
  47. }
  48. /**
  49. * @return string
  50. */
  51. public function getMemoryLeak()
  52. {
  53. return "Memory delta: " . MetricsFormatter::getPrettySizeFromBytes($this->getMemoryUsage() - $this->memoryStart);
  54. }
  55. /**
  56. * @return string
  57. */
  58. public function __toString()
  59. {
  60. return "Time elapsed: " . $this->getTime() . "s";
  61. }
  62. /**
  63. * @return float
  64. */
  65. private function getMicrotime()
  66. {
  67. list($micro_seconds, $seconds) = explode(" ", microtime());
  68. return ((float)$micro_seconds + (float)$seconds);
  69. }
  70. /**
  71. * Returns current memory usage, if available
  72. *
  73. * @return int
  74. */
  75. private function getMemoryUsage()
  76. {
  77. if (function_exists('memory_get_usage')) {
  78. return memory_get_usage();
  79. }
  80. return 0;
  81. }
  82. }