Test Failed
Push — feat/cache-warming ( 037623...493f4d )
by Chema
04:16
created

PerformanceMetrics::formatElapsedTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Console\Application\CacheWarm;
6
7
use function memory_get_usage;
8
use function microtime;
9
use function sprintf;
10
11
final class PerformanceMetrics
12
{
13
    private readonly float $startTime;
14
15
    private readonly int $startMemory;
16
17
    public function __construct()
18
    {
19
        $this->startTime = microtime(true);
0 ignored issues
show
Bug introduced by
The property startTime is declared read-only in Gacela\Console\Applicati...Warm\PerformanceMetrics.
Loading history...
20
        $this->startMemory = memory_get_usage(true);
0 ignored issues
show
Bug introduced by
The property startMemory is declared read-only in Gacela\Console\Applicati...Warm\PerformanceMetrics.
Loading history...
21
    }
22
23
    public function getElapsedTime(): float
24
    {
25
        return microtime(true) - $this->startTime;
26
    }
27
28
    public function getMemoryUsed(): int
29
    {
30
        return memory_get_usage(true) - $this->startMemory;
31
    }
32
33
    public function formatElapsedTime(): string
34
    {
35
        return sprintf('%.3f seconds', $this->getElapsedTime());
36
    }
37
38
    public function formatMemoryUsed(): string
39
    {
40
        return $this->formatBytes($this->getMemoryUsed());
41
    }
42
43
    private function formatBytes(int $bytes): string
44
    {
45
        if ($bytes < 1024) {
46
            return sprintf('%d B', $bytes);
47
        }
48
49
        if ($bytes < 1048576) {
50
            return sprintf('%.2f KB', $bytes / 1024);
51
        }
52
53
        return sprintf('%.2f MB', $bytes / 1048576);
54
    }
55
}
56