Passed
Push — dev ( 8e8e3b...6bb8f6 )
by Dispositif
03:16 queued 15s
created

Memory   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 43
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A echoMemory() 0 7 2
A memoryPeak() 0 5 1
A __construct() 0 2 1
A convert() 0 5 1
A memoryUsage() 0 5 1
1
<?php
2
/**
3
 * This file is part of dispositif/wikibot application (@github)
4
 * 2019/2020 © Philippe M. <[email protected]>
5
 * For the full copyright and MIT license information, please view the license file.
6
 */
7
8
namespace App\Infrastructure;
9
10
/**
11
 * php -i | grep memory
12
 * Class Memory.
13
 */
14
class Memory
15
{
16
    public function __construct()
17
    {
18
    }
19
20
    /**
21
     * $real=true shows allocated memory (-> system monitoring)
22
     * $real=null|false shows memory used by script (-> memory leak search)
23
     * Do not take PHP external resources into account (remote/DB connection, SimpleXML, etc)
24
     * See http://drib.tech/programming/get-real-amount-memory-allocated-php.
25
     *
26
     * @param bool|null $real
27
     */
28
    public function echoMemory(?bool $real = null): void
29
    {
30
        echo sprintf(
31
            "Memory %s: %s %s \n",
32
            ($real) ? '(true)' : '',
33
            $this->memoryUsage(),
34
            $this->memoryPeak()
35
        );
36
    }
37
38
    public function memoryUsage(?bool $real = null): string
39
    {
40
        $memUsage = memory_get_usage($real);
41
42
        return sprintf('usage: %s', $this->convert($memUsage));
43
    }
44
45
    public function memoryPeak(?bool $real = null): string
46
    {
47
        $memUsage = memory_get_peak_usage($real);
48
49
        return sprintf('peak: %s', $this->convert($memUsage));
50
    }
51
52
    private function convert(int $size): string
53
    {
54
        $unit = ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
55
56
        return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2).' '.$unit[intval($i)];
57
    }
58
}
59