3 * @copyright Copyright (C) 2010-2022, 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\ValueObject\Cache;
25 use Friendica\Core\Config\Capability\IManageConfigValues;
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(): bool
66 return $this->rendertime;
70 * Updates the enabling of the current profiler
72 * @param IManageConfigValues $config
74 public function update(IManageConfigValues $config)
76 $this->enabled = $config->get('system', 'profiler');
77 $this->rendertime = $config->get('rendertime', 'callstack');
81 * @param \Friendica\Core\Config\ValueObject\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
97 public function startRecording(string $value)
99 if (!$this->enabled) {
103 $this->timestamps[] = ['value' => $value, 'stamp' => microtime(true), 'credit' => 0];
107 * Stop a profiler recording
109 * @param string $callstack
113 public function stopRecording(string $callstack = '')
115 if (!$this->enabled || empty($this->timestamps)) {
119 $timestamp = array_pop($this->timestamps);
121 $duration = floatval(microtime(true) - $timestamp['stamp'] - $timestamp['credit']);
122 $value = $timestamp['value'];
124 foreach ($this->timestamps as $key => $stamp) {
125 $this->timestamps[$key]['credit'] += $duration;
128 $callstack = $callstack ?: System::callstack(4, $value == 'rendering' ? 0 : 1);
130 if (!isset($this->performance[$value])) {
131 $this->performance[$value] = 0;
134 $this->performance[$value] += (float) $duration;
135 $this->performance['marktime'] += (float) $duration;
137 if (!isset($this->callstack[$value][$callstack])) {
138 // Prevent ugly E_NOTICE
139 $this->callstack[$value][$callstack] = 0;
142 $this->callstack[$value][$callstack] += (float) $duration;
146 * Saves a timestamp for a value - f.e. a call
147 * Necessary for profiling Friendica
149 * @param int $timestamp the Timestamp
150 * @param string $value A value to profile
151 * @param string $callstack A callstack string, generated if absent
155 public function saveTimestamp(int $timestamp, string $value, string $callstack = '')
157 if (!$this->enabled) {
161 $callstack = $callstack ?: System::callstack(4, 1);
163 $duration = floatval(microtime(true) - $timestamp);
165 if (!isset($this->performance[$value])) {
166 // Prevent ugly E_NOTICE
167 $this->performance[$value] = 0;
170 $this->performance[$value] += (float) $duration;
171 $this->performance['marktime'] += (float) $duration;
173 if (!isset($this->callstack[$value][$callstack])) {
174 // Prevent ugly E_NOTICE
175 $this->callstack[$value][$callstack] = 0;
178 $this->callstack[$value][$callstack] += (float) $duration;
182 * Resets the performance and callstack profiling
186 public function reset()
188 $this->resetPerformance();
189 $this->resetCallstack();
193 * Resets the performance profiling data
197 public function resetPerformance()
199 $this->performance = [];
200 $this->performance['start'] = microtime(true);
201 $this->performance['ready'] = 0;
202 $this->performance['database'] = 0;
203 $this->performance['database_write'] = 0;
204 $this->performance['cache'] = 0;
205 $this->performance['cache_write'] = 0;
206 $this->performance['network'] = 0;
207 $this->performance['file'] = 0;
208 $this->performance['rendering'] = 0;
209 $this->performance['session'] = 0;
210 $this->performance['marktime'] = 0;
211 $this->performance['marktime'] = microtime(true);
212 $this->performance['classcreate'] = 0;
213 $this->performance['classinit'] = 0;
214 $this->performance['init'] = 0;
215 $this->performance['content'] = 0;
219 * Resets the callstack profiling data
223 public function resetCallstack()
225 $this->callstack = [];
226 $this->callstack['database'] = [];
227 $this->callstack['database_write'] = [];
228 $this->callstack['cache'] = [];
229 $this->callstack['cache_write'] = [];
230 $this->callstack['network'] = [];
231 $this->callstack['file'] = [];
232 $this->callstack['rendering'] = [];
233 $this->callstack['session'] = [];
237 * Returns the rendertime string
238 * @param float $limit Minimal limit for displaying the execution duration
240 * @return string the rendertime
242 public function getRendertimeString(float $limit = 0): string
246 if (!$this->enabled || !$this->rendertime) {
250 if (isset($this->callstack['database'])) {
251 $output .= "\nDatabase Read:\n";
252 foreach ($this->callstack['database'] as $func => $time) {
253 $time = round($time, 3);
254 if ($time > $limit) {
255 $output .= $func . ': ' . $time . "\n";
260 if (isset($this->callstack['database_write'])) {
261 $output .= "\nDatabase Write:\n";
262 foreach ($this->callstack['database_write'] as $func => $time) {
263 $time = round($time, 3);
264 if ($time > $limit) {
265 $output .= $func . ': ' . $time . "\n";
270 if (isset($this->callstack['cache'])) {
271 $output .= "\nCache Read:\n";
272 foreach ($this->callstack['cache'] as $func => $time) {
273 $time = round($time, 3);
274 if ($time > $limit) {
275 $output .= $func . ': ' . $time . "\n";
280 if (isset($this->callstack['cache_write'])) {
281 $output .= "\nCache Write:\n";
282 foreach ($this->callstack['cache_write'] as $func => $time) {
283 $time = round($time, 3);
284 if ($time > $limit) {
285 $output .= $func . ': ' . $time . "\n";
290 if (isset($this->callstack['network'])) {
291 $output .= "\nNetwork:\n";
292 foreach ($this->callstack['network'] as $func => $time) {
293 $time = round($time, 3);
294 if ($time > $limit) {
295 $output .= $func . ': ' . $time . "\n";
300 if (isset($this->callstack['rendering'])) {
301 $output .= "\nRendering:\n";
302 foreach ($this->callstack['rendering'] as $func => $time) {
303 $time = round($time, 3);
304 if ($time > $limit) {
305 $output .= $func . ': ' . $time . "\n";
314 * Save the current profiling data to a log entry
316 * @param LoggerInterface $logger The logger to save the current log
317 * @param string $message Additional message for the log
321 public function saveLog(LoggerInterface $logger, string $message = '')
323 $duration = microtime(true) - $this->get('start');
327 'action' => 'profiling',
328 'database_read' => round($this->get('database') - $this->get('database_write'), 3),
329 'database_write' => round($this->get('database_write'), 3),
330 'cache_read' => round($this->get('cache'), 3),
331 'cache_write' => round($this->get('cache_write'), 3),
332 'network_io' => round($this->get('network'), 2),
333 'file_io' => round($this->get('file'), 2),
334 'other_io' => round($duration - ($this->get('database')
335 + $this->get('cache') + $this->get('cache_write')
336 + $this->get('network') + $this->get('file')), 2),
337 'total' => round($duration, 2)
341 if ($this->isRendertime()) {
342 $output = $this->getRendertimeString();
343 $logger->info($message . ": " . $output, ['action' => 'profiling']);
348 * Finds an entry of the container by its identifier and returns it.
350 * @param string $id Identifier of the entry to look for.
352 * @throws NotFoundExceptionInterface No entry was found for **this** identifier.
353 * @throws ContainerExceptionInterface Error while retrieving the entry.
357 public function get(string $id): int
359 if (!$this->has($id)) {
362 return $this->performance[$id];
366 public function set($timestamp, string $id)
368 $this->performance[$id] = $timestamp;
372 * Returns true if the container can return an entry for the given identifier.
373 * Returns false otherwise.
375 * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
376 * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
378 * @param string $id Identifier of the entry to look for.
382 public function has(string $id): bool
384 return isset($this->performance[$id]);