3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
24 use Friendica\Core\Config\Cache;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\System;
27 use Psr\Container\ContainerExceptionInterface;
28 use Psr\Container\ContainerInterface;
29 use Psr\Container\NotFoundExceptionInterface;
30 use Psr\Log\LoggerInterface;
33 * A class to store profiling data
34 * It can handle different logging data for specific functions or global performance measures
36 * It stores the data as log entries (@see LoggerInterface)
38 class Profiler implements ContainerInterface
41 * @var array The global performance array
45 * @var array The function specific callstack
49 * @var bool True, if the Profiler is enabled
53 * @var bool True, if the Profiler should measure the whole rendertime including functions
57 private $timestamps = [];
60 * True, if the Profiler should measure the whole rendertime including functions
64 public function isRendertime()
66 return $this->rendertime;
70 * Updates the enabling of the current profiler
72 * @param IConfig $config
74 public function update(IConfig $config)
76 $this->enabled = $config->get('system', 'profiler');
77 $this->rendertime = $config->get('rendertime', 'callstack');
81 * @param Cache $configCache The configuration cache
83 public function __construct(Cache $configCache)
85 $this->enabled = $configCache->get('system', 'profiler');
86 $this->rendertime = $configCache->get('rendertime', 'callstack');
91 * Start a profiler recording
93 * @param string $value
96 public function startRecording(string $value)
98 if (!$this->enabled) {
102 $this->timestamps[] = ['value' => $value, 'stamp' => microtime(true), 'credit' => 0];
106 * Stop a profiler recording
108 * @param string $callstack
111 public function stopRecording(string $callstack = '')
113 if (!$this->enabled || empty($this->timestamps)) {
117 $timestamp = array_pop($this->timestamps);
119 $duration = floatval(microtime(true) - $timestamp['stamp'] - $timestamp['credit']);
120 $value = $timestamp['value'];
122 foreach ($this->timestamps as $key => $stamp) {
123 $this->timestamps[$key]['credit'] += $duration;
126 $callstack = $callstack ?: System::callstack(4, $value == 'rendering' ? 0 : 1);
128 if (!isset($this->performance[$value])) {
129 $this->performance[$value] = 0;
132 $this->performance[$value] += (float) $duration;
133 $this->performance['marktime'] += (float) $duration;
135 if (!isset($this->callstack[$value][$callstack])) {
136 // Prevent ugly E_NOTICE
137 $this->callstack[$value][$callstack] = 0;
140 $this->callstack[$value][$callstack] += (float) $duration;
144 * Saves a timestamp for a value - f.e. a call
145 * Necessary for profiling Friendica
147 * @param int $timestamp the Timestamp
148 * @param string $value A value to profile
149 * @param string $callstack A callstack string, generated if absent
151 public function saveTimestamp($timestamp, $value, $callstack = '')
153 if (!$this->enabled) {
157 $callstack = $callstack ?: System::callstack(4, 1);
159 $duration = floatval(microtime(true) - $timestamp);
161 if (!isset($this->performance[$value])) {
162 // Prevent ugly E_NOTICE
163 $this->performance[$value] = 0;
166 $this->performance[$value] += (float) $duration;
167 $this->performance['marktime'] += (float) $duration;
169 if (!isset($this->callstack[$value][$callstack])) {
170 // Prevent ugly E_NOTICE
171 $this->callstack[$value][$callstack] = 0;
174 $this->callstack[$value][$callstack] += (float) $duration;
178 * Resets the performance and callstack profiling
180 public function reset()
182 $this->resetPerformance();
183 $this->resetCallstack();
187 * Resets the performance profiling data
189 public function resetPerformance()
191 $this->performance = [];
192 $this->performance['start'] = microtime(true);
193 $this->performance['ready'] = 0;
194 $this->performance['database'] = 0;
195 $this->performance['database_write'] = 0;
196 $this->performance['cache'] = 0;
197 $this->performance['cache_write'] = 0;
198 $this->performance['network'] = 0;
199 $this->performance['file'] = 0;
200 $this->performance['rendering'] = 0;
201 $this->performance['session'] = 0;
202 $this->performance['marktime'] = 0;
203 $this->performance['marktime'] = microtime(true);
204 $this->performance['classcreate'] = 0;
205 $this->performance['classinit'] = 0;
206 $this->performance['init'] = 0;
207 $this->performance['content'] = 0;
211 * Resets the callstack profiling data
213 public function resetCallstack()
215 $this->callstack = [];
216 $this->callstack['database'] = [];
217 $this->callstack['database_write'] = [];
218 $this->callstack['cache'] = [];
219 $this->callstack['cache_write'] = [];
220 $this->callstack['network'] = [];
221 $this->callstack['file'] = [];
222 $this->callstack['rendering'] = [];
223 $this->callstack['session'] = [];
227 * Returns the rendertime string
228 * @param float $limit Minimal limit for displaying the execution duration
230 * @return string the rendertime
232 public function getRendertimeString(float $limit = 0)
236 if (!$this->enabled || !$this->rendertime) {
240 if (isset($this->callstack["database"])) {
241 $output .= "\nDatabase Read:\n";
242 foreach ($this->callstack["database"] as $func => $time) {
243 $time = round($time, 3);
244 if ($time > $limit) {
245 $output .= $func . ": " . $time . "\n";
249 if (isset($this->callstack["database_write"])) {
250 $output .= "\nDatabase Write:\n";
251 foreach ($this->callstack["database_write"] as $func => $time) {
252 $time = round($time, 3);
253 if ($time > $limit) {
254 $output .= $func . ": " . $time . "\n";
258 if (isset($this->callstack["cache"])) {
259 $output .= "\nCache Read:\n";
260 foreach ($this->callstack["cache"] as $func => $time) {
261 $time = round($time, 3);
262 if ($time > $limit) {
263 $output .= $func . ": " . $time . "\n";
267 if (isset($this->callstack["cache_write"])) {
268 $output .= "\nCache Write:\n";
269 foreach ($this->callstack["cache_write"] as $func => $time) {
270 $time = round($time, 3);
271 if ($time > $limit) {
272 $output .= $func . ": " . $time . "\n";
276 if (isset($this->callstack["network"])) {
277 $output .= "\nNetwork:\n";
278 foreach ($this->callstack["network"] as $func => $time) {
279 $time = round($time, 3);
280 if ($time > $limit) {
281 $output .= $func . ": " . $time . "\n";
286 if (isset($this->callstack["rendering"])) {
287 $output .= "\nRendering:\n";
288 foreach ($this->callstack["rendering"] as $func => $time) {
289 $time = round($time, 3);
290 if ($time > $limit) {
291 $output .= $func . ": " . $time . "\n";
300 * Save the current profiling data to a log entry
302 * @param LoggerInterface $logger The logger to save the current log
303 * @param string $message Additional message for the log
305 public function saveLog(LoggerInterface $logger, $message = '')
307 $duration = microtime(true) - $this->get('start');
311 'action' => 'profiling',
312 'database_read' => round($this->get('database') - $this->get('database_write'), 3),
313 'database_write' => round($this->get('database_write'), 3),
314 'cache_read' => round($this->get('cache'), 3),
315 'cache_write' => round($this->get('cache_write'), 3),
316 'network_io' => round($this->get('network'), 2),
317 'file_io' => round($this->get('file'), 2),
318 'other_io' => round($duration - ($this->get('database')
319 + $this->get('cache') + $this->get('cache_write')
320 + $this->get('network') + $this->get('file')), 2),
321 'total' => round($duration, 2)
325 if ($this->isRendertime()) {
326 $output = $this->getRendertimeString();
327 $logger->info($message . ": " . $output, ['action' => 'profiling']);
332 * Finds an entry of the container by its identifier and returns it.
334 * @param string $id Identifier of the entry to look for.
336 * @throws NotFoundExceptionInterface No entry was found for **this** identifier.
337 * @throws ContainerExceptionInterface Error while retrieving the entry.
341 public function get($id)
343 if (!$this->has($id)) {
346 return $this->performance[$id];
350 public function set($timestamp, $id)
352 $this->performance[$id] = $timestamp;
356 * Returns true if the container can return an entry for the given identifier.
357 * Returns false otherwise.
359 * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
360 * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
362 * @param string $id Identifier of the entry to look for.
366 public function has($id)
368 return isset($this->performance[$id]);