1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace tomzx\Profiler; |
4
|
|
|
|
5
|
|
|
use tomzx\Profiler\Runtime\CallFrame; |
6
|
|
|
|
7
|
|
|
class StackBasedProfiler |
8
|
|
|
{ |
9
|
|
|
private $lastTick; |
10
|
|
|
private $profile; |
11
|
|
|
private $stack = []; |
12
|
|
|
|
13
|
|
|
public function start() |
14
|
|
|
{ |
15
|
|
|
$this->lastTick = microtime(true); |
16
|
|
|
$this->profile = new Profile(); |
17
|
|
|
$this->profile->startTime = $this->getMicroseconds($this->lastTick); |
|
|
|
|
18
|
|
|
|
19
|
|
|
$rootProfileNode = new ProfileNode(); |
20
|
|
|
$rootProfileNode->callFrame = new CallFrame('(root)', 0, '', -1, -1); |
21
|
|
|
$this->profile->nodes[] = $rootProfileNode; |
22
|
|
|
$this->stack[] = $rootProfileNode; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function stop(): Profile |
26
|
|
|
{ |
27
|
|
|
$this->profile->endTime = $this->getMicroseconds(microtime(true)); |
|
|
|
|
28
|
|
|
return $this->profile; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function push($name) |
32
|
|
|
{ |
33
|
|
|
$tick = microtime(true); |
34
|
|
|
|
35
|
|
|
$profileNode = new ProfileNode(); |
36
|
|
|
|
37
|
|
|
$callFrame = new CallFrame($name, 0, '', -1, -1); |
38
|
|
|
|
39
|
|
|
$profileNode->callFrame = $callFrame; |
40
|
|
|
++$profileNode->hitCount; |
41
|
|
|
|
42
|
|
|
/** @var \tomzx\Profiler\ProfileNode $parent */ |
43
|
|
|
$parent = end($this->stack); |
44
|
|
|
$this->profile->nodes[] = $profileNode; |
45
|
|
|
$this->profile->samples[] = $profileNode->id; |
46
|
|
|
$this->profile->timeDeltas[] = $this->getMicroseconds($tick - $this->lastTick); |
47
|
|
|
$this->lastTick = $tick; |
48
|
|
|
|
49
|
|
|
$parent->children[] = $profileNode->id; |
50
|
|
|
|
51
|
|
|
$this->stack[$name] = $profileNode; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function pop() |
55
|
|
|
{ |
56
|
|
|
array_pop($this->stack); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function getMicroseconds($time): int |
60
|
|
|
{ |
61
|
|
|
return (int)(($time) * 10 ** 6); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
This check looks for assignments to scalar types that may be of the wrong type.
To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.