Created
July 20, 2018 09:10
-
-
Save mleko/887370e8223ee159a7ecc79c3bfb41c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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