1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @maintainer Timur Shagiakhmetov <[email protected]> |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Badoo\LiveProfiler; |
8
|
|
|
|
9
|
|
|
class SimpleProfiler |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var self |
13
|
|
|
*/ |
14
|
|
|
private static $instance; |
15
|
|
|
|
16
|
|
|
private $methods = []; |
17
|
|
|
/** @var \SplStack */ |
18
|
|
|
private $stack; |
19
|
|
|
private $is_enabled = false; |
20
|
|
|
|
21
|
|
|
public static function getInstance() |
22
|
|
|
{ |
23
|
|
|
if (self::$instance === null) { |
24
|
|
|
self::$instance = new static(); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return self::$instance; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function enable() |
31
|
|
|
{ |
32
|
|
|
$this->is_enabled= true; |
33
|
|
|
$this->stack = new \SplStack(); |
34
|
|
|
|
35
|
|
|
$this->startTimer('main()'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function disable() |
39
|
|
|
{ |
40
|
|
|
$this->endTimer('main()'); |
41
|
|
|
|
42
|
|
|
if (!$this->stack->isEmpty()) { |
43
|
|
|
return []; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$this->is_enabled = false; |
47
|
|
|
|
48
|
|
|
return $this->methods; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function startTimer($tag) |
52
|
|
|
{ |
53
|
|
|
if (!$this->is_enabled) { |
54
|
|
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$full_method = $this->getFullMethod($tag); |
58
|
|
|
$this->stack->push($tag); |
59
|
|
|
|
60
|
|
|
if (!isset($this->methods[$full_method])) { |
61
|
|
|
$this->methods[$full_method] = [ |
62
|
|
|
'wt' => 0, |
63
|
|
|
'ct' => 0, |
64
|
|
|
]; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$time = (int)(microtime(true) * 1e6); |
68
|
|
|
$this->methods[$full_method]['wt'] = $time - $this->methods[$full_method]['wt']; |
69
|
|
|
|
70
|
|
|
return true; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function endTimer($tag) |
74
|
|
|
{ |
75
|
|
|
if (!$this->is_enabled) { |
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if ($this->stack->isEmpty() || $this->stack->top() !== $tag) { |
80
|
|
|
return false; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$tag = $this->stack->pop(); |
84
|
|
|
|
85
|
|
|
$full_method = $this->getFullMethod($tag); |
86
|
|
|
|
87
|
|
|
$time = (int)(microtime(true) * 1e6); |
88
|
|
|
$this->methods[$full_method]['ct']++; |
89
|
|
|
$this->methods[$full_method]['wt'] = $time - $this->methods[$full_method]['wt']; |
90
|
|
|
|
91
|
|
|
return true; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
private function getFullMethod($tag) |
95
|
|
|
{ |
96
|
|
|
if ($this->stack->isEmpty()) { |
97
|
|
|
return $tag; |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
return $this->stack->top() . '==>' . $tag; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|