| 148 |
lars |
1 |
<?php declare(strict_types=1);
|
|
|
2 |
/*
|
|
|
3 |
* This file is part of phpunit/php-timer.
|
|
|
4 |
*
|
|
|
5 |
* (c) Sebastian Bergmann <sebastian@phpunit.de>
|
|
|
6 |
*
|
|
|
7 |
* For the full copyright and license information, please view the LICENSE
|
|
|
8 |
* file that was distributed with this source code.
|
|
|
9 |
*/
|
|
|
10 |
namespace SebastianBergmann\Timer;
|
|
|
11 |
|
|
|
12 |
use function is_float;
|
|
|
13 |
use function memory_get_peak_usage;
|
|
|
14 |
use function microtime;
|
|
|
15 |
use function sprintf;
|
|
|
16 |
|
|
|
17 |
final class ResourceUsageFormatter
|
|
|
18 |
{
|
|
|
19 |
/**
|
|
|
20 |
* @psalm-var array<string,int>
|
|
|
21 |
*/
|
|
|
22 |
private const SIZES = [
|
|
|
23 |
'GB' => 1073741824,
|
|
|
24 |
'MB' => 1048576,
|
|
|
25 |
'KB' => 1024,
|
|
|
26 |
];
|
|
|
27 |
|
|
|
28 |
public function resourceUsage(Duration $duration): string
|
|
|
29 |
{
|
|
|
30 |
return sprintf(
|
|
|
31 |
'Time: %s, Memory: %s',
|
|
|
32 |
$duration->asString(),
|
|
|
33 |
$this->bytesToString(memory_get_peak_usage(true))
|
|
|
34 |
);
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
/**
|
|
|
38 |
* @throws TimeSinceStartOfRequestNotAvailableException
|
|
|
39 |
*/
|
|
|
40 |
public function resourceUsageSinceStartOfRequest(): string
|
|
|
41 |
{
|
|
|
42 |
if (!isset($_SERVER['REQUEST_TIME_FLOAT'])) {
|
|
|
43 |
throw new TimeSinceStartOfRequestNotAvailableException(
|
|
|
44 |
'Cannot determine time at which the request started because $_SERVER[\'REQUEST_TIME_FLOAT\'] is not available'
|
|
|
45 |
);
|
|
|
46 |
}
|
|
|
47 |
|
|
|
48 |
if (!is_float($_SERVER['REQUEST_TIME_FLOAT'])) {
|
|
|
49 |
throw new TimeSinceStartOfRequestNotAvailableException(
|
|
|
50 |
'Cannot determine time at which the request started because $_SERVER[\'REQUEST_TIME_FLOAT\'] is not of type float'
|
|
|
51 |
);
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
return $this->resourceUsage(
|
|
|
55 |
Duration::fromMicroseconds(
|
|
|
56 |
(1000000 * (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']))
|
|
|
57 |
)
|
|
|
58 |
);
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
private function bytesToString(int $bytes): string
|
|
|
62 |
{
|
|
|
63 |
foreach (self::SIZES as $unit => $value) {
|
|
|
64 |
if ($bytes >= $value) {
|
|
|
65 |
return sprintf('%.2f %s', $bytes >= 1024 ? $bytes / $value : $bytes, $unit);
|
|
|
66 |
}
|
|
|
67 |
}
|
|
|
68 |
|
|
|
69 |
// @codeCoverageIgnoreStart
|
|
|
70 |
return $bytes . ' byte' . ($bytes !== 1 ? 's' : '');
|
|
|
71 |
// @codeCoverageIgnoreEnd
|
|
|
72 |
}
|
|
|
73 |
}
|