mts7 / php-execution-timer
可测试的PHP计时器
1.2.3
2024-02-14 15:11 UTC
Requires
- php: ^8.1
Requires (Dev)
- mts7/php-code-quality: ^0.1.17
- phpunit/phpunit: ^9.6
- roave/security-advisories: dev-latest
README
用于跟踪和累计时长的PHP计时器
安装
composer require mts7/php-execution-timer
使用方法
单次测量
在测量单个事件的时间时,使用getDuration
来找到在该特定功能上花费的时间量。
$timer = new \MtsTimer\Timer(); $timer->start(); doSomething(); $timer->stop(); echo 'Duration: ' . $timer->getDuration() . PHP_EOL;
多次测量
在测量多个事件的时间时,使用getTotalDuration
来找到所有包含的功能的总时长。
$timer = new \MtsTimer\Timer(); for ($i = 0; $i < 5; $i++) { $timer->start(); doSomething(); $timer->stop(); echo 'Something took ' . $timer->getDuration() . ' seconds.' . PHP_EOL; } echo 'Total duration: ' . $timer->getTotalDuration() . PHP_EOL;
测量之间的重置
某些情况下需要具有多个独立跟踪的累计。对于这些,使用reset
来清除计时器并将所有内部值重置为0.0
。
$timer = new \MtsTimer\Timer(); $timings = []; for ($i = 0; $i < 3; $i++) { $timer->reset(); for ($j = 0; $j < 5; $j++) { $timer->start(); doSomething(); $timer->stop(); } $timings[] = $timer->getTotalDuration(); }
使用FixedTimer进行测试
代码中的常规计时器是Timer
,而测试将使用FixedTimer
而不更改代码。拥有TimerInterface
是使用组合的好处。由于Timer
和FixedTimer
都具有类似的功能,因此基础功能包含在AbstractTimer
中,并在必要时重写方法。
FixedTimer
使用两个常数(固定)值(而不是时间):一个用于开始,另一个用于停止。
示例
这些是非常简单的示例,展示了使用计时器的类以及使用该类和测试该类的类。在实际场景中,使用一个容器进行依赖注入,以及一个接受时间的可调用对象。
class Benchmark { public function __construct(private \MtsTimer\TimerInterface $timer) { } public function run(callable $callable): float { $this->timer->start(); $callable(); $this->timer->stop(); return $this->timer->getDuration(); } } class RunTheBenchmark { public function execute(): float { $timer = new \MtsTimer\Timer(); $benchmark = new Benchmark($timer); return $benchmark->run([self::class, 'doNothing']); } public static function doNothing(): void { } } class BenchmarkTest { public function testRun(): void { $timer = new \MtsTimer\FixedTimer(); $benchmark = new Benchmark($timer); $duration = $benchmark->run([RunTheBenchmark::class, 'doNothing']); $this->assertSame($timer::DURATION, $duration); } }