]> git.mxchange.org Git - friendica.git/blob - src/Util/Profiler.php
Merge pull request #8277 from MrPetovan/task/8251-use-about-for-pdesc
[friendica.git] / src / Util / Profiler.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Config\Cache;
25 use Friendica\Core\Config\IConfig;
26 use Psr\Container\ContainerExceptionInterface;
27 use Psr\Container\ContainerInterface;
28 use Psr\Container\NotFoundExceptionInterface;
29 use Psr\Log\LoggerInterface;
30
31 /**
32  * A class to store profiling data
33  * It can handle different logging data for specific functions or global performance measures
34  *
35  * It stores the data as log entries (@see LoggerInterface)
36  */
37 class Profiler implements ContainerInterface
38 {
39         /**
40          * @var array The global performance array
41          */
42         private $performance;
43         /**
44          * @var array The function specific callstack
45          */
46         private $callstack;
47         /**
48          * @var bool True, if the Profiler is enabled
49          */
50         private $enabled;
51         /**
52          * @var bool True, if the Profiler should measure the whole rendertime including functions
53          */
54         private $rendertime;
55
56         /**
57          * True, if the Profiler should measure the whole rendertime including functions
58          *
59          * @return bool
60          */
61         public function isRendertime()
62         {
63                 return $this->rendertime;
64         }
65
66         /**
67          * Updates the enabling of the current profiler
68          *
69          * @param IConfig $config
70          */
71         public function update(IConfig $config)
72         {
73                 $this->enabled = $config->get('system', 'profiler');
74                 $this->rendertime = $config->get('rendertime', 'callstack');
75         }
76
77         /**
78          * @param Cache $configCache The configuration cache
79          */
80         public function __construct(Cache $configCache)
81         {
82                 $this->enabled = $configCache->get('system', 'profiler');
83                 $this->rendertime = $configCache->get('rendertime', 'callstack');
84                 $this->reset();
85         }
86
87         /**
88          * Saves a timestamp for a value - f.e. a call
89          * Necessary for profiling Friendica
90          *
91          * @param int $timestamp the Timestamp
92          * @param string $value A value to profile
93          * @param string $callstack The callstack of the current profiling data
94          */
95         public function saveTimestamp($timestamp, $value, $callstack = '')
96         {
97                 if (!$this->enabled) {
98                         return;
99                 }
100
101                 $duration = floatval(microtime(true) - $timestamp);
102
103                 if (!isset($this->performance[$value])) {
104                         // Prevent ugly E_NOTICE
105                         $this->performance[$value] = 0;
106                 }
107
108                 $this->performance[$value] += (float) $duration;
109                 $this->performance['marktime'] += (float) $duration;
110
111                 if (!isset($this->callstack[$value][$callstack])) {
112                         // Prevent ugly E_NOTICE
113                         $this->callstack[$value][$callstack] = 0;
114                 }
115
116                 $this->callstack[$value][$callstack] += (float) $duration;
117         }
118
119         /**
120          * Resets the performance and callstack profiling
121          */
122         public function reset()
123         {
124                 $this->resetPerformance();
125                 $this->resetCallstack();
126         }
127
128         /**
129          * Resets the performance profiling data
130          */
131         public function resetPerformance()
132         {
133                 $this->performance = [];
134                 $this->performance['start'] = microtime(true);
135                 $this->performance['database'] = 0;
136                 $this->performance['database_write'] = 0;
137                 $this->performance['cache'] = 0;
138                 $this->performance['cache_write'] = 0;
139                 $this->performance['network'] = 0;
140                 $this->performance['file'] = 0;
141                 $this->performance['rendering'] = 0;
142                 $this->performance['parser'] = 0;
143                 $this->performance['marktime'] = 0;
144                 $this->performance['marktime'] = microtime(true);
145         }
146
147         /**
148          * Resets the callstack profiling data
149          */
150         public function resetCallstack()
151         {
152                 $this->callstack = [];
153                 $this->callstack['database'] = [];
154                 $this->callstack['database_write'] = [];
155                 $this->callstack['cache'] = [];
156                 $this->callstack['cache_write'] = [];
157                 $this->callstack['network'] = [];
158                 $this->callstack['file'] = [];
159                 $this->callstack['rendering'] = [];
160                 $this->callstack['parser'] = [];
161         }
162
163         /**
164          * Returns the rendertime string
165          *
166          * @return string the rendertime
167          */
168         public function getRendertimeString()
169         {
170                 $output = '';
171
172                 if (!$this->enabled || !$this->rendertime) {
173                         return $output;
174                 }
175
176                 if (isset($this->callstack["database"])) {
177                         $output .= "\nDatabase Read:\n";
178                         foreach ($this->callstack["database"] as $func => $time) {
179                                 $time = round($time, 3);
180                                 if ($time > 0) {
181                                         $output .= $func . ": " . $time . "\n";
182                                 }
183                         }
184                 }
185                 if (isset($this->callstack["database_write"])) {
186                         $output .= "\nDatabase Write:\n";
187                         foreach ($this->callstack["database_write"] as $func => $time) {
188                                 $time = round($time, 3);
189                                 if ($time > 0) {
190                                         $output .= $func . ": " . $time . "\n";
191                                 }
192                         }
193                 }
194                 if (isset($this->callstack["cache"])) {
195                         $output .= "\nCache Read:\n";
196                         foreach ($this->callstack["cache"] as $func => $time) {
197                                 $time = round($time, 3);
198                                 if ($time > 0) {
199                                         $output .= $func . ": " . $time . "\n";
200                                 }
201                         }
202                 }
203                 if (isset($this->callstack["cache_write"])) {
204                         $output .= "\nCache Write:\n";
205                         foreach ($this->callstack["cache_write"] as $func => $time) {
206                                 $time = round($time, 3);
207                                 if ($time > 0) {
208                                         $output .= $func . ": " . $time . "\n";
209                                 }
210                         }
211                 }
212                 if (isset($this->callstack["network"])) {
213                         $output .= "\nNetwork:\n";
214                         foreach ($this->callstack["network"] as $func => $time) {
215                                 $time = round($time, 3);
216                                 if ($time > 0) {
217                                         $output .= $func . ": " . $time . "\n";
218                                 }
219                         }
220                 }
221
222                 return $output;
223         }
224
225         /**
226          * Save the current profiling data to a log entry
227          *
228          * @param LoggerInterface $logger  The logger to save the current log
229          * @param string          $message Additional message for the log
230          */
231         public function saveLog(LoggerInterface $logger, $message = '')
232         {
233                 $duration = microtime(true) - $this->get('start');
234                 $logger->info(
235                         $message,
236                         [
237                                 'action' => 'profiling',
238                                 'database_read' => round($this->get('database') - $this->get('database_write'), 3),
239                                 'database_write' => round($this->get('database_write'), 3),
240                                 'cache_read' => round($this->get('cache'), 3),
241                                 'cache_write' => round($this->get('cache_write'), 3),
242                                 'network_io' => round($this->get('network'), 2),
243                                 'file_io' => round($this->get('file'), 2),
244                                 'other_io' => round($duration - ($this->get('database')
245                                                 + $this->get('cache') + $this->get('cache_write')
246                                                 + $this->get('network') + $this->get('file')), 2),
247                                 'total' => round($duration, 2)
248                         ]
249                 );
250
251                 if ($this->isRendertime()) {
252                         $output = $this->getRendertimeString();
253                         $logger->info($message . ": " . $output, ['action' => 'profiling']);
254                 }
255         }
256
257         /**
258          * Finds an entry of the container by its identifier and returns it.
259          *
260          * @param string $id Identifier of the entry to look for.
261          *
262          * @throws NotFoundExceptionInterface  No entry was found for **this** identifier.
263          * @throws ContainerExceptionInterface Error while retrieving the entry.
264          *
265          * @return int Entry.
266          */
267         public function get($id)
268         {
269                 if (!$this->has($id)) {
270                         return 0;
271                 } else {
272                         return $this->performance[$id];
273                 }
274         }
275
276         /**
277          * Returns true if the container can return an entry for the given identifier.
278          * Returns false otherwise.
279          *
280          * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
281          * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
282          *
283          * @param string $id Identifier of the entry to look for.
284          *
285          * @return bool
286          */
287         public function has($id)
288         {
289                 return isset($this->performance[$id]);
290         }
291 }