2022-09-13 15:13:11 +02:00
|
|
|
<?php
|
|
|
|
// Timings.php
|
|
|
|
// Created: 2022-02-16
|
2024-08-01 22:16:38 +00:00
|
|
|
// Updated: 2024-08-01
|
2022-09-13 15:13:11 +02:00
|
|
|
|
|
|
|
namespace Index\Performance;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Represents a Stopwatch with timing points.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
class Timings {
|
|
|
|
private Stopwatch $sw;
|
|
|
|
private int|float $lastLapTicks;
|
|
|
|
private array $laps;
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* @param ?Stopwatch $sw Stopwatch to measure timing points from, null to start a new one.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function __construct(?Stopwatch $sw = null) {
|
|
|
|
$this->sw = $sw ?? Stopwatch::startNew();
|
|
|
|
$this->lastLapTicks = $this->sw->getElapsedTicks();
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Gets the underlying stopwatch object.
|
|
|
|
*
|
|
|
|
* @return Stopwatch Stopwatch object.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function getStopwatch(): Stopwatch {
|
|
|
|
return $this->sw;
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Returns timing points.
|
|
|
|
*
|
|
|
|
* @return TimingPoint[] Timing points.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function getLaps(): array {
|
|
|
|
return $this->laps;
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Starts the underlying stopwatch.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function start(): void {
|
|
|
|
$this->sw->start();
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Stops the underlying stopwatch.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function stop(): void {
|
|
|
|
$this->sw->stop();
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Checks whether the underlying stopwatch is running.
|
|
|
|
*
|
|
|
|
* @return bool true if it is running.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function isRunning(): bool {
|
|
|
|
return $this->sw->isRunning();
|
|
|
|
}
|
|
|
|
|
2024-08-01 22:16:38 +00:00
|
|
|
/**
|
|
|
|
* Record a timing point.
|
|
|
|
*
|
|
|
|
* @param string $name Timing point name, must be alphanumeric.
|
|
|
|
* @param string $comment Timing point comment.
|
|
|
|
* @throws InvalidArgumentException If $name is not alphanumeric.
|
|
|
|
*/
|
2022-09-13 15:13:11 +02:00
|
|
|
public function lap(string $name, string $comment = ''): void {
|
|
|
|
if(!ctype_alnum($name))
|
2024-08-01 22:16:38 +00:00
|
|
|
throw new InvalidArgumentException('$name must be alphanumeric.');
|
2022-09-13 15:13:11 +02:00
|
|
|
|
|
|
|
$lapTicks = $this->sw->getElapsedTicks();
|
|
|
|
$elapsed = $lapTicks - $this->lastLapTicks;
|
|
|
|
$this->lastLapTicks = $lapTicks;
|
|
|
|
|
|
|
|
$this->laps[] = new TimingPoint(
|
|
|
|
$lapTicks,
|
|
|
|
$elapsed,
|
|
|
|
$name,
|
|
|
|
$comment
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|