Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 9 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
Timing | |
0.00% |
0 / 9 |
|
0.00% |
0 / 4 |
30 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
millis | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
end | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
6 | |||
start | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 |
1 | <?php |
2 | declare( strict_types = 1 ); |
3 | |
4 | namespace Wikimedia\Parsoid\Utils; |
5 | |
6 | use Wikimedia\Assert\Assert; |
7 | |
8 | /** |
9 | * A helper class to make it easier to compute timing metrics. |
10 | */ |
11 | class Timing { |
12 | /** |
13 | * This is typically a StatsdDataFactoryInterface, but really could be |
14 | * anything which has a `timing()` method. Set it to `null` to disable |
15 | * metrics. |
16 | * |
17 | * @var ?object |
18 | */ |
19 | private $metrics; |
20 | /* @var float */ |
21 | private $startTime; |
22 | |
23 | private function __construct( ?object $metrics ) { |
24 | $this->metrics = $metrics; |
25 | $this->startTime = self::millis(); |
26 | } |
27 | |
28 | /** |
29 | * Return the current number of milliseconds since the epoch, as a float. |
30 | */ |
31 | public static function millis(): float { |
32 | return 1000 * microtime( true ); |
33 | } |
34 | |
35 | /** |
36 | * End this timing measurement, reporting it under the given `name`. |
37 | * @param ?string $name |
38 | * @return float Number of milliseconds reported |
39 | */ |
40 | public function end( ?string $name = null ): float { |
41 | $elapsed = self::millis() - $this->startTime; |
42 | if ( $this->metrics ) { |
43 | Assert::invariant( $name !== null, 'Recording metric without a key.' ); |
44 | $this->metrics->timing( $name, $elapsed ); |
45 | } |
46 | return $elapsed; |
47 | } |
48 | |
49 | /** |
50 | * Start a timing measurement, logging it to the given `$metrics` object |
51 | * (which just needs to have a `timing()` method). |
52 | * @param ?object $metrics |
53 | * @return Timing |
54 | */ |
55 | public static function start( ?object $metrics = null ): Timing { |
56 | return new Timing( $metrics ); |
57 | } |
58 | } |