Skip to content

Instantly share code, notes, and snippets.

@mleko
Created July 20, 2018 09:10
Show Gist options
  • Save mleko/887370e8223ee159a7ecc79c3bfb41c0 to your computer and use it in GitHub Desktop.
Save mleko/887370e8223ee159a7ecc79c3bfb41c0 to your computer and use it in GitHub Desktop.
<?php
class Stopwatch
{
/**
* @var array[]
*/
private $marks = [];
/**
* @var float|null
*/
private $lastMark = null;
/**
* Mark point in time
*
* @param string $label
*
* @return float
*/
public function mark(string $label = ""): float
{
$now = microtime(true);
$this->marks[] = ["time" => $now, "label" => $label];
$diff = null !== $this->lastMark ? $now - $this->lastMark : 0;
$this->lastMark = $now;
return $diff;
}
/**
* Get all marks
*
* @return array[] ["total" => float, "split" => float, "label" => string][]
*/
public function getMarks(): array
{
$marks = [];
$first = $last = reset($this->marks)["time"];
foreach ($this->marks as $mark) {
$marks[] = ["total" => $mark["time"] - $first, "split" => $mark["time"] - $last, "label" => $mark["label"]];
$last = $mark["time"];
}
return $marks;
}
/**
* Get time elapsed between first and last mark
*
* @return float
*/
public function elapsed(): float
{
return null !== $this->lastMark ? $this->lastMark - $this->marks[0]["time"] : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment