index/src/Performance/Stopwatch.php

73 lines
1.8 KiB
PHP

<?php
// Stopwatch.php
// Created: 2021-04-26
// Updated: 2022-02-16
namespace Index\Performance;
/**
* Provides a means to measure elapsed time at a high resolution.
*/
class Stopwatch {
private int|float $start = -1;
private int|float $elapsed = 0;
private int|float $frequency;
public function __construct() {
$this->frequency = PerformanceCounter::getFrequency();
}
public function start(): void {
if($this->start < 0)
$this->start = PerformanceCounter::getTicks();
}
public function stop(): void {
if($this->start < 0)
return;
$this->elapsed += PerformanceCounter::getTicksSince($this->start);
$this->start = -1;
}
/**
* Checks whether the Stopwatch is currently running.
*
* @return bool true if the Stopwatch is running, false if not.
*/
public function isRunning(): bool {
return $this->start >= 0;
}
/**
* Gets the number of ticks that have elapsed.
*
* @return int|float Number of ticks.
*/
public function getElapsedTicks(): int|float {
$elapsed = $this->elapsed;
if($this->start >= 0)
$elapsed += PerformanceCounter::getTicksSince($this->start);
return $elapsed;
}
/**
* Gets the number of elapsed milliseconds.
*
* @return float Number of elapsed milliseconds.
*/
public function getElapsedTime(): float {
return $this->getElapsedTicks() / $this->frequency;
}
/**
* Creates a new Stopwatch instance and starts measuring time.
*
* @return Stopwatch Newly created running Stopwatch.
*/
public static function startNew(): Stopwatch {
$sw = new Stopwatch;
$sw->start();
return $sw;
}
}