DebugMemory.php
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since DebugKit 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace DebugKit;
use Cake\Error\Debugger;
/**
* Contains methods for Profiling memory usage.
*
*/
class DebugMemory
{
/**
* An array of recorded memory use points.
*
* @var array
*/
protected static $_points = [];
/**
* Get current memory usage
*
* @return int number of bytes ram currently in use. 0 if memory_get_usage() is not available.
*/
public static function getCurrent()
{
return memory_get_usage();
}
/**
* Get peak memory use
*
* @return int peak memory use (in bytes). Returns 0 if memory_get_peak_usage() is not available
*/
public static function getPeak()
{
return memory_get_peak_usage();
}
/**
* Stores a memory point in the internal tracker.
* Takes a optional message name which can be used to identify the memory point.
* If no message is supplied a debug_backtrace will be done to identify the memory point.
*
* @param string $message Message to identify this memory point.
* @return bool
*/
public static function record($message = null)
{
$memoryUse = self::getCurrent();
if (!$message) {
$trace = debug_backtrace();
$message = Debugger::trimPath($trace[0]['file']) . ' line ' . $trace[0]['line'];
}
if (isset(self::$_points[$message])) {
$originalMessage = $message;
$i = 1;
while (isset(self::$_points[$message])) {
$i++;
$message = $originalMessage . ' #' . $i;
}
}
self::$_points[$message] = $memoryUse;
return true;
}
/**
* Get all the stored memory points
*
* @param bool $clear Whether you want to clear the memory points as well. Defaults to false.
* @return array Array of memory marks stored so far.
*/
public static function getAll($clear = false)
{
$marks = self::$_points;
if ($clear) {
self::$_points = [];
}
return $marks;
}
/**
* Clear out any existing memory points
*
* @return void
*/
public static function clear()
{
self::$_points = [];
}
}