3 * @copyright Copyright (C) 2010-2023, 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\Capability\IManageConfigValues;
25 use Friendica\Core\System;
26 use Psr\Container\ContainerExceptionInterface;
27 use Psr\Container\ContainerInterface;
28 use Psr\Container\NotFoundExceptionInterface;
29 use Psr\Log\LoggerInterface;
32 * A class to store profiling data
33 * It can handle different logging data for specific functions or global performance measures
35 * It stores the data as log entries (@see LoggerInterface)
37 class Profiler implements ContainerInterface
40 * @var array The global performance array
44 * @var array The function specific callstack
48 * @var bool True, if the Profiler is enabled
52 * @var bool True, if the Profiler should measure the whole rendertime including functions
56 private $timestamps = [];
59 * True, if the Profiler should measure the whole rendertime including functions
63 public function isRendertime(): bool
65 return $this->rendertime;
68 public function __construct(IManageConfigValues $config)
70 $this->enabled = (bool)$config->get('system', 'profiler') ?? false;
71 $this->rendertime = (bool)$config->get('rendertime', 'callstack') ?? false;
76 * Start a profiler recording
78 * @param string $value
82 public function startRecording(string $value)
84 if (!$this->enabled) {
88 $this->timestamps[] = ['value' => $value, 'stamp' => microtime(true), 'credit' => 0];
92 * Stop a profiler recording
94 * @param string $callstack
98 public function stopRecording(string $callstack = '')
100 if (!$this->enabled || empty($this->timestamps)) {
104 $timestamp = array_pop($this->timestamps);
106 $duration = floatval(microtime(true) - $timestamp['stamp'] - $timestamp['credit']);
107 $value = $timestamp['value'];
109 foreach ($this->timestamps as $key => $stamp) {
110 $this->timestamps[$key]['credit'] += $duration;
113 $callstack = $callstack ?: System::callstack(4, $value == 'rendering' ? 0 : 1);
115 if (!isset($this->performance[$value])) {
116 $this->performance[$value] = 0;
119 $this->performance[$value] += (float)$duration;
120 $this->performance['marktime'] += (float)$duration;
122 if (!isset($this->callstack[$value][$callstack])) {
123 // Prevent ugly E_NOTICE
124 $this->callstack[$value][$callstack] = 0;
127 $this->callstack[$value][$callstack] += (float)$duration;
131 * Saves a timestamp for a value - f.e. a call
132 * Necessary for profiling Friendica
134 * @param float $timestamp the Timestamp
135 * @param string $value A value to profile
136 * @param string $callstack A callstack string, generated if absent
140 public function saveTimestamp(float $timestamp, string $value, string $callstack = '')
142 if (!$this->enabled) {
146 $callstack = $callstack ?: System::callstack(4, 1);
148 $duration = floatval(microtime(true) - $timestamp);
150 if (!isset($this->performance[$value])) {
151 // Prevent ugly E_NOTICE
152 $this->performance[$value] = 0;
155 $this->performance[$value] += (float)$duration;
156 $this->performance['marktime'] += (float)$duration;
158 if (!isset($this->callstack[$value][$callstack])) {
159 // Prevent ugly E_NOTICE
160 $this->callstack[$value][$callstack] = 0;
163 $this->callstack[$value][$callstack] += (float)$duration;
167 * Resets the performance and callstack profiling
171 public function reset()
173 $this->resetPerformance();
174 $this->resetCallstack();
178 * Resets the performance profiling data
182 public function resetPerformance()
184 $this->performance = [];
185 $this->performance['start'] = microtime(true);
186 $this->performance['ready'] = 0;
187 $this->performance['database'] = 0;
188 $this->performance['database_write'] = 0;
189 $this->performance['cache'] = 0;
190 $this->performance['cache_write'] = 0;
191 $this->performance['network'] = 0;
192 $this->performance['file'] = 0;
193 $this->performance['rendering'] = 0;
194 $this->performance['session'] = 0;
195 $this->performance['marktime'] = microtime(true);
196 $this->performance['classcreate'] = 0;
197 $this->performance['classinit'] = 0;
198 $this->performance['init'] = 0;
199 $this->performance['content'] = 0;
203 * Resets the callstack profiling data
207 public function resetCallstack()
209 $this->callstack = [];
210 $this->callstack['database'] = [];
211 $this->callstack['database_write'] = [];
212 $this->callstack['cache'] = [];
213 $this->callstack['cache_write'] = [];
214 $this->callstack['network'] = [];
215 $this->callstack['file'] = [];
216 $this->callstack['rendering'] = [];
217 $this->callstack['session'] = [];
221 * Returns the rendertime string
223 * @param float $limit Minimal limit for displaying the execution duration
225 * @return string the rendertime
227 public function getRendertimeString(float $limit = 0): string
231 if (!$this->enabled || !$this->rendertime) {
235 if (isset($this->callstack['database'])) {
236 $output .= "\nDatabase Read:\n";
237 foreach ($this->callstack['database'] as $func => $time) {
238 $time = round($time, 3);
239 if ($time > $limit) {
240 $output .= $func . ': ' . $time . "\n";
245 if (isset($this->callstack['database_write'])) {
246 $output .= "\nDatabase Write:\n";
247 foreach ($this->callstack['database_write'] as $func => $time) {
248 $time = round($time, 3);
249 if ($time > $limit) {
250 $output .= $func . ': ' . $time . "\n";
255 if (isset($this->callstack['cache'])) {
256 $output .= "\nCache Read:\n";
257 foreach ($this->callstack['cache'] as $func => $time) {
258 $time = round($time, 3);
259 if ($time > $limit) {
260 $output .= $func . ': ' . $time . "\n";
265 if (isset($this->callstack['cache_write'])) {
266 $output .= "\nCache Write:\n";
267 foreach ($this->callstack['cache_write'] as $func => $time) {
268 $time = round($time, 3);
269 if ($time > $limit) {
270 $output .= $func . ': ' . $time . "\n";
275 if (isset($this->callstack['network'])) {
276 $output .= "\nNetwork:\n";
277 foreach ($this->callstack['network'] as $func => $time) {
278 $time = round($time, 3);
279 if ($time > $limit) {
280 $output .= $func . ': ' . $time . "\n";
285 if (isset($this->callstack['rendering'])) {
286 $output .= "\nRendering:\n";
287 foreach ($this->callstack['rendering'] as $func => $time) {
288 $time = round($time, 3);
289 if ($time > $limit) {
290 $output .= $func . ': ' . $time . "\n";
299 * Save the current profiling data to a log entry
301 * @param LoggerInterface $logger The logger to save the current log
302 * @param string $message Additional message for the log
306 public function saveLog(LoggerInterface $logger, string $message = '')
308 $duration = microtime(true) - $this->get('start');
312 'action' => 'profiling',
313 'database_read' => round($this->get('database') - $this->get('database_write'), 3),
314 'database_write' => round($this->get('database_write'), 3),
315 'cache_read' => round($this->get('cache'), 3),
316 'cache_write' => round($this->get('cache_write'), 3),
317 'network_io' => round($this->get('network'), 2),
318 'file_io' => round($this->get('file'), 2),
319 'other_io' => round($duration - ($this->get('database')
320 + $this->get('cache') + $this->get('cache_write')
321 + $this->get('network') + $this->get('file')), 2),
322 'total' => round($duration, 2)
326 if ($this->isRendertime()) {
327 $output = $this->getRendertimeString();
328 $logger->info($message . ": " . $output, ['action' => 'profiling']);
333 * Finds an entry of the container by its identifier and returns it.
335 * @param string $id Identifier of the entry to look for.
337 * @return float Entry.
338 * @throws ContainerExceptionInterface Error while retrieving the entry.
340 * @throws NotFoundExceptionInterface No entry was found for **this** identifier.
342 public function get(string $id): float
344 if (!$this->has($id)) {
347 return $this->performance[$id];
351 public function set($timestamp, string $id)
353 $this->performance[$id] = $timestamp;
357 * Returns true if the container can return an entry for the given identifier.
358 * Returns false otherwise.
360 * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
361 * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
363 * @param string $id Identifier of the entry to look for.
367 public function has(string $id): bool
369 return isset($this->performance[$id]);