index/src/Performance/Timings.php

56 lines
1.2 KiB
PHP

<?php
// Timings.php
// Created: 2022-02-16
// Updated: 2022-02-16
namespace Index\Performance;
use InvalidArgumentException;
class Timings {
private Stopwatch $sw;
private int|float $lastLapTicks;
private array $laps;
public function __construct(?Stopwatch $sw = null) {
$this->sw = $sw ?? Stopwatch::startNew();
$this->lastLapTicks = $this->sw->getElapsedTicks();
}
public function getStopwatch(): Stopwatch {
return $this->sw;
}
public function getLaps(): array {
return $this->laps;
}
public function start(): void {
$this->sw->start();
}
public function stop(): void {
$this->sw->stop();
}
public function isRunning(): bool {
return $this->sw->isRunning();
}
public function lap(string $name, string $comment = ''): void {
if(!ctype_alnum($name))
throw new InvalidArgumentException('$name must be alpha-numeric.');
$lapTicks = $this->sw->getElapsedTicks();
$elapsed = $lapTicks - $this->lastLapTicks;
$this->lastLapTicks = $lapTicks;
$this->laps[] = new TimingPoint(
$lapTicks,
$elapsed,
$name,
$comment
);
}
}