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.

104 lines
2.2 KiB

3 years ago
  1. # phpunit/php-timer
  2. [![CI Status](https://github.com/sebastianbergmann/php-timer/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/php-timer/actions)
  3. [![Type Coverage](https://shepherd.dev/github/sebastianbergmann/php-timer/coverage.svg)](https://shepherd.dev/github/sebastianbergmann/php-timer)
  4. Utility class for timing things, factored out of PHPUnit into a stand-alone component.
  5. ## Installation
  6. You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/):
  7. ```
  8. composer require phpunit/php-timer
  9. ```
  10. If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency:
  11. ```
  12. composer require --dev phpunit/php-timer
  13. ```
  14. ## Usage
  15. ### Basic Timing
  16. ```php
  17. require __DIR__ . '/vendor/autoload.php';
  18. use SebastianBergmann\Timer\Timer;
  19. $timer = new Timer;
  20. $timer->start();
  21. foreach (\range(0, 100000) as $i) {
  22. // ...
  23. }
  24. $duration = $timer->stop();
  25. var_dump(get_class($duration));
  26. var_dump($duration->asString());
  27. var_dump($duration->asSeconds());
  28. var_dump($duration->asMilliseconds());
  29. var_dump($duration->asMicroseconds());
  30. var_dump($duration->asNanoseconds());
  31. ```
  32. The code above yields the output below:
  33. ```
  34. string(32) "SebastianBergmann\Timer\Duration"
  35. string(9) "00:00.002"
  36. float(0.002851062)
  37. float(2.851062)
  38. float(2851.062)
  39. int(2851062)
  40. ```
  41. ### Resource Consumption
  42. #### Explicit duration
  43. ```php
  44. require __DIR__ . '/vendor/autoload.php';
  45. use SebastianBergmann\Timer\ResourceUsageFormatter;
  46. use SebastianBergmann\Timer\Timer;
  47. $timer = new Timer;
  48. $timer->start();
  49. foreach (\range(0, 100000) as $i) {
  50. // ...
  51. }
  52. print (new ResourceUsageFormatter)->resourceUsage($timer->stop());
  53. ```
  54. The code above yields the output below:
  55. ```
  56. Time: 00:00.002, Memory: 6.00 MB
  57. ```
  58. #### Duration since PHP Startup (using unreliable `$_SERVER['REQUEST_TIME_FLOAT']`)
  59. ```php
  60. require __DIR__ . '/vendor/autoload.php';
  61. use SebastianBergmann\Timer\ResourceUsageFormatter;
  62. foreach (\range(0, 100000) as $i) {
  63. // ...
  64. }
  65. print (new ResourceUsageFormatter)->resourceUsageSinceStartOfRequest();
  66. ```
  67. The code above yields the output below:
  68. ```
  69. Time: 00:00.002, Memory: 6.00 MB
  70. ```