sfTimer.class.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfTimer class allows to time some PHP code.
  11. *
  12. * @package symfony
  13. * @subpackage util
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfTimer.class.php 9079 2008-05-20 00:38:07Z Carl.Vondrick $
  16. */
  17. class sfTimer
  18. {
  19. protected
  20. $startTime = null,
  21. $totalTime = null,
  22. $name = '',
  23. $calls = 0;
  24. /**
  25. * Creates a new sfTimer instance.
  26. *
  27. * @param string $name The name of the timer
  28. */
  29. public function __construct($name = '')
  30. {
  31. $this->name = $name;
  32. $this->startTimer();
  33. }
  34. /**
  35. * Starts the timer.
  36. */
  37. public function startTimer()
  38. {
  39. $this->startTime = microtime(true);
  40. }
  41. /**
  42. * Stops the timer and add the amount of time since the start to the total time.
  43. *
  44. * @return float Time spend for the last call
  45. */
  46. public function addTime()
  47. {
  48. $spend = microtime(true) - $this->startTime;
  49. $this->totalTime += $spend;
  50. ++$this->calls;
  51. return $spend;
  52. }
  53. /**
  54. * Gets the number of calls this timer has been called to time code.
  55. *
  56. * @return integer Number of calls
  57. */
  58. public function getCalls()
  59. {
  60. return $this->calls;
  61. }
  62. /**
  63. * Gets the total time elapsed for all calls of this timer.
  64. *
  65. * @return float Time in seconds
  66. */
  67. public function getElapsedTime()
  68. {
  69. if (null === $this->totalTime)
  70. {
  71. $this->addTime();
  72. }
  73. return $this->totalTime;
  74. }
  75. }