index/src/Performance/Timings.php

92 lines
2.1 KiB
PHP
Raw Normal View History

2022-09-13 15:13:11 +02:00
<?php
// Timings.php
// Created: 2022-02-16
// Updated: 2024-08-03
2022-09-13 15:13:11 +02:00
namespace Index\Performance;
use InvalidArgumentException;
/**
* Represents a Stopwatch with timing points.
*/
2022-09-13 15:13:11 +02:00
class Timings {
private Stopwatch $sw;
private int $lastLapTicks;
/** @var TimingPoint[] */
2022-09-13 15:13:11 +02:00
private array $laps;
/**
* @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();
}
/**
* Gets the underlying stopwatch object.
*
* @return Stopwatch Stopwatch object.
*/
2022-09-13 15:13:11 +02:00
public function getStopwatch(): Stopwatch {
return $this->sw;
}
/**
* Returns timing points.
*
* @return TimingPoint[] Timing points.
*/
2022-09-13 15:13:11 +02:00
public function getLaps(): array {
return $this->laps;
}
/**
* Starts the underlying stopwatch.
*/
2022-09-13 15:13:11 +02:00
public function start(): void {
$this->sw->start();
}
/**
* Stops the underlying stopwatch.
*/
2022-09-13 15:13:11 +02:00
public function stop(): void {
$this->sw->stop();
}
/**
* 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();
}
/**
* 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))
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
);
}
}