TimerTest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Drupal\Tests\Component\Utility;
  3. use Drupal\Component\Utility\Timer;
  4. use PHPUnit\Framework\TestCase;
  5. /**
  6. * Tests the Timer system.
  7. *
  8. * @group Utility
  9. *
  10. * @coversDefaultClass \Drupal\Component\Utility\Timer
  11. */
  12. class TimerTest extends TestCase {
  13. /**
  14. * Tests Timer::read() time accumulation accuracy across multiple restarts.
  15. *
  16. * @covers ::start
  17. * @covers ::stop
  18. * @covers ::read
  19. */
  20. public function testTimer() {
  21. Timer::start('test');
  22. usleep(5000);
  23. $value = Timer::read('test');
  24. usleep(5000);
  25. $value2 = Timer::read('test');
  26. usleep(5000);
  27. $value3 = Timer::read('test');
  28. usleep(5000);
  29. $value4 = Timer::read('test');
  30. // Although we sleep for 5 milliseconds, we should test that at least 4 ms
  31. // have past because usleep() is not reliable on Windows. See
  32. // http://php.net/manual/function.usleep.php for more information. The
  33. // purpose of the test to validate that the Timer class can measure elapsed
  34. // time not the granularity of usleep() on a particular OS.
  35. $this->assertGreaterThanOrEqual(4, $value, 'Timer failed to measure at least 4 milliseconds of sleeping while running.');
  36. $this->assertGreaterThanOrEqual($value + 4, $value2, 'Timer failed to measure at least 8 milliseconds of sleeping while running.');
  37. $this->assertGreaterThanOrEqual($value2 + 4, $value3, 'Timer failed to measure at least 12 milliseconds of sleeping while running.');
  38. $this->assertGreaterThanOrEqual($value3 + 4, $value4, 'Timer failed to measure at least 16 milliseconds of sleeping while running.');
  39. // Stop the timer.
  40. $value5 = Timer::stop('test');
  41. $this->assertGreaterThanOrEqual($value4, $value5['time'], 'Timer measured after stopping was not greater than last measurement.');
  42. // Read again.
  43. $value6 = Timer::read('test');
  44. $this->assertEquals($value5['time'], $value6, 'Timer measured after stopping was not equal to the stopped time.');
  45. // Restart.
  46. Timer::start('test');
  47. usleep(5000);
  48. $value7 = Timer::read('test');
  49. $this->assertGreaterThanOrEqual($value6 + 4, $value7, 'Timer failed to measure at least 16 milliseconds of sleeping while running.');
  50. // Stop again.
  51. $value8 = Timer::stop('test');
  52. $value9 = Timer::read('test');
  53. $this->assertEquals($value8['time'], $value9, 'Timer measured after stopping not equal to stop time.');
  54. }
  55. }