christiaanbye / stopwatch
极致简单的执行时间测量
0.3.0
2021-08-07 10:06 UTC
Requires
- php: ^5.4 || ^7.0 || ^8.0
Requires (Dev)
- christiaanbye/polyfill-each: ^1.0
- phpunit/phpunit: ^4.8
This package is auto-updated.
Last update: 2024-09-07 17:56:42 UTC
README
正如其名,这是一个用于在PHP中分析代码的辅助工具。该库设计考虑了以下几点
- 最小化开销。你之所以阅读这篇文档,可能是因为你有一个或多个需要分析的小任务。在结果中添加几百毫秒的开销并不会对任何人有益。
- 简单的API。没有关于如何呈现结果或如何命名测量实例的决策。只需简单地开始和停止,中间可能有一些圈。如果你需要更高级的功能,代码分析可能不是最适合你用例的方法。
- 与旧版PHP版本的最大兼容性。我们大多数人都经历过与已到生命尽头的PHP版本一起工作的乐趣。幸运的是,存在版本控制,所以可以安装他们选择的库的旧版本。不幸的是,这有时是以公共API的微妙改变为代价的。我宁愿减少心理摩擦而不是增加,这样你就可以使用相同的库,从古老的PHP 5.6到现代的PHP 8。
先决条件
- PHP 5.4或更高版本
安装
可以使用Composer轻松安装
composer require christiaanbye/stopwatch
高级用户可能会提倡添加--dev
标志,并依赖他们的质量门来检测未定义的Stopwatch类的使用,以防止意外的生产使用。
使用方法
对于基本使用,您可以使用start()
、stop()
和elapsed()
方法
use Stopwatch\Stopwatch; Stopwatch::start(); // Start the stopwatch // ... run your tasks here echo Stopwatch::elapsed(); // Optionally take a peek at the elapsed time // ... run some more tasks here Stopwatch::stop(); // Stop the stopwatch once your tasks have ran echo Stopwatch::elapsed(); // Output the time elapsed between the moment the stopwatch was started and stopped
elapsed()
方法返回以下之一的一个浮点数
- 如果计时器仍在运行,则从开始计时器到现在经过的时间
- 如果计时器已停止,则从开始到停止经过的时间
后者在您希望进一步记录执行时间时非常有用。
在更复杂的使用案例中,还可以结合使用split()
方法和getSplits()
方法。这允许您记录任务之间的中间时间
use Stopwatch\Stopwatch; Stopwatch::start(); // ... run a first batch of tasks here Stopwatch::split('1st batch of tasks'); // ... run a second batch of tasks here Stopwatch::split('2nd batch of tasks'); // ... run a third batch of tasks here Stopwatch::split('3rd batch of tasks'); // ... optionally run more tasks for which an intermediate time is not necessary Stopwatch::stop(); print_r(Stopwatch::getSplits()); // Output the time elapsed between the moment the stopwatch was started and stopped
getSplits()
方法返回所有中间时间和总时间作为一个包含以下内容的数组
- 自开始计时器以来经过的时间
- 上一次和当前中间之间的时间
上述代码的结果如下
Array
(
[1st batch of tasks] => Array
(
[sinceStart] => 0.007193305
)
[2nd batch of tasks] => Array
(
[sinceStart] => 0.012397519
[sincePreviousSplit] => 0.005204214
)
[3rd batch of tasks] => Array
(
[sinceStart] => 0.01354921
[sincePreviousSplit] => 0.001151691
)
[overall] => Array
(
[sinceStart] => 0.01888658
)
)
与elapsed()
方法类似,可以在调用getSplits()
之前停止计时器,这样记录的执行时间就不会受到运行时日志延迟的影响。