Passed
Pull Request — master (#26)
by Wanderson
02:55
created

Benchmark::getTime()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 8
nop 0
dl 0
loc 17
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace Win\Services;
4
5
/**
6
 * Contador de Desempenho
7
 *
8
 * Usado para analisar desempenho de códigos
9
 *
10
 * <code>
11
 * $b = new Benchmark();
12
 * [code here]
13
 * echo $b->getTime();
14
 * </code>
15
 */
16
class Benchmark
17
{
18
	private int $startTime;
19
	private int $memory;
20
21
	/**
22
	 * Inicia a contagem de tempo
23
	 */
24
	public function __construct()
25
	{
26
		$this->startTime = microtime(true);
27
		$this->memory = memory_get_usage();
28
	}
29
30
	/**
31
	 * Reinicia a contagem de tempo
32
	 */
33
	public function reset()
34
	{
35
		$this->startTime = microtime(true);
36
		$this->memory = memory_get_usage();
37
	}
38
39
	/**
40
	 * Retorna o tempo gasto (em microssegundos)
41
	 * @return float
42
	 */
43
	private function getMicroTime()
44
	{
45
		return microtime(true) - $this->startTime;
46
	}
47
48
	/**
49
	 * Retorna o tempo gasto (na unidade correta)
50
	 * @return string
51
	 */
52
	public function getTime()
53
	{
54
		$sec = $this->getMicroTime();
55
		$day = floor($sec / 86400);
56
		$sec -= $day * 86400;
57
		$hour = floor($sec / 3600);
58
		$sec -= $hour * 3600;
59
		$minute = floor($sec / 60);
60
		$sec -= $minute * 60;
61
		$microSec = ($sec - floor($sec)) * 1000;
62
63
		return
64
				(empty($day) ? '' : $day . 'd ') .
65
				(empty($hour) ? '' : $hour . 'h ') .
66
				(empty($minute) ? '' : $minute . 'm ') .
67
				floor($sec) . 's ' .
68
				$microSec . 'ms';
69
	}
70
71
	/**
72
	 * Retorna a quantidade de memória gasta
73
	 * @return int
74
	 */
75
	public function getMemory()
76
	{
77
		return (memory_get_usage() - $this->memory) / (1024 * 1024);
78
	}
79
}
80