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 * Note: The reason there are two different ways of updating the configuration of this class is because it can
73 * be used even with no available database connection which IManageConfigValues doesn't ensure.
75 * @param IManageConfigValues $config
77 public function update(IManageConfigValues $config)
79 $this->enabled = (bool) $config->get('system', 'profiler') ?? false;
80 $this->rendertime = (bool) $config->get('rendertime', 'callstack') ?? false;
84 * Note: The reason we are using a Config Cache object to initialize this class is to ensure it'll work even with no
85 * available database connection.
87 * @param \Friendica\Core\Config\ValueObject\Cache $configCache The configuration cache
89 public function __construct(Cache $configCache)
91 $this->enabled = (bool) $configCache->get('system', 'profiler') ?? false;
92 $this->rendertime = (bool) $configCache->get('rendertime', 'callstack') ?? false;
97 * Start a profiler recording
99 * @param string $value
103 public function startRecording(string $value)
105 if (!$this->enabled) {
109 $this->timestamps[] = ['value' => $value, 'stamp' => microtime(true), 'credit' => 0];
113 * Stop a profiler recording
115 * @param string $callstack
119 public function stopRecording(string $callstack = '')
121 if (!$this->enabled || empty($this->timestamps)) {
125 $timestamp = array_pop($this->timestamps);
127 $duration = floatval(microtime(true) - $timestamp['stamp'] - $timestamp['credit']);
128 $value = $timestamp['value'];
130 foreach ($this->timestamps as $key => $stamp) {
131 $this->timestamps[$key]['credit'] += $duration;
134 $callstack = $callstack ?: System::callstack(4, $value == 'rendering' ? 0 : 1);
136 if (!isset($this->performance[$value])) {
137 $this->performance[$value] = 0;
140 $this->performance[$value] += (float) $duration;
141 $this->performance['marktime'] += (float) $duration;
143 if (!isset($this->callstack[$value][$callstack])) {
144 // Prevent ugly E_NOTICE
145 $this->callstack[$value][$callstack] = 0;
148 $this->callstack[$value][$callstack] += (float) $duration;
152 * Saves a timestamp for a value - f.e. a call
153 * Necessary for profiling Friendica
155 * @param int $timestamp the Timestamp
156 * @param string $value A value to profile
157 * @param string $callstack A callstack string, generated if absent
161 public function saveTimestamp(int $timestamp, string $value, string $callstack = '')
163 if (!$this->enabled) {
167 $callstack = $callstack ?: System::callstack(4, 1);
169 $duration = floatval(microtime(true) - $timestamp);
171 if (!isset($this->performance[$value])) {
172 // Prevent ugly E_NOTICE
173 $this->performance[$value] = 0;
176 $this->performance[$value] += (float) $duration;
177 $this->performance['marktime'] += (float) $duration;
179 if (!isset($this->callstack[$value][$callstack])) {
180 // Prevent ugly E_NOTICE
181 $this->callstack[$value][$callstack] = 0;
184 $this->callstack[$value][$callstack] += (float) $duration;
188 * Resets the performance and callstack profiling
192 public function reset()
194 $this->resetPerformance();
195 $this->resetCallstack();
199 * Resets the performance profiling data
203 public function resetPerformance()
205 $this->performance = [];
206 $this->performance['start'] = microtime(true);
207 $this->performance['ready'] = 0;
208 $this->performance['database'] = 0;
209 $this->performance['database_write'] = 0;
210 $this->performance['cache'] = 0;
211 $this->performance['cache_write'] = 0;
212 $this->performance['network'] = 0;
213 $this->performance['file'] = 0;
214 $this->performance['rendering'] = 0;
215 $this->performance['session'] = 0;
216 $this->performance['marktime'] = 0;
217 $this->performance['marktime'] = microtime(true);
218 $this->performance['classcreate'] = 0;
219 $this->performance['classinit'] = 0;
220 $this->performance['init'] = 0;
221 $this->performance['content'] = 0;
225 * Resets the callstack profiling data
229 public function resetCallstack()
231 $this->callstack = [];
232 $this->callstack['database'] = [];
233 $this->callstack['database_write'] = [];
234 $this->callstack['cache'] = [];
235 $this->callstack['cache_write'] = [];
236 $this->callstack['network'] = [];
237 $this->callstack['file'] = [];
238 $this->callstack['rendering'] = [];
239 $this->callstack['session'] = [];
243 * Returns the rendertime string
244 * @param float $limit Minimal limit for displaying the execution duration
246 * @return string the rendertime
248 public function getRendertimeString(float $limit = 0): string
252 if (!$this->enabled || !$this->rendertime) {
256 if (isset($this->callstack['database'])) {
257 $output .= "\nDatabase Read:\n";
258 foreach ($this->callstack['database'] as $func => $time) {
259 $time = round($time, 3);
260 if ($time > $limit) {
261 $output .= $func . ': ' . $time . "\n";
266 if (isset($this->callstack['database_write'])) {
267 $output .= "\nDatabase Write:\n";
268 foreach ($this->callstack['database_write'] as $func => $time) {
269 $time = round($time, 3);
270 if ($time > $limit) {
271 $output .= $func . ': ' . $time . "\n";
276 if (isset($this->callstack['cache'])) {
277 $output .= "\nCache Read:\n";
278 foreach ($this->callstack['cache'] as $func => $time) {
279 $time = round($time, 3);
280 if ($time > $limit) {
281 $output .= $func . ': ' . $time . "\n";
286 if (isset($this->callstack['cache_write'])) {
287 $output .= "\nCache Write:\n";
288 foreach ($this->callstack['cache_write'] as $func => $time) {
289 $time = round($time, 3);
290 if ($time > $limit) {
291 $output .= $func . ': ' . $time . "\n";
296 if (isset($this->callstack['network'])) {
297 $output .= "\nNetwork:\n";
298 foreach ($this->callstack['network'] as $func => $time) {
299 $time = round($time, 3);
300 if ($time > $limit) {
301 $output .= $func . ': ' . $time . "\n";
306 if (isset($this->callstack['rendering'])) {
307 $output .= "\nRendering:\n";
308 foreach ($this->callstack['rendering'] as $func => $time) {
309 $time = round($time, 3);
310 if ($time > $limit) {
311 $output .= $func . ': ' . $time . "\n";
320 * Save the current profiling data to a log entry
322 * @param LoggerInterface $logger The logger to save the current log
323 * @param string $message Additional message for the log
327 public function saveLog(LoggerInterface $logger, string $message = '')
329 $duration = microtime(true) - $this->get('start');
333 'action' => 'profiling',
334 'database_read' => round($this->get('database') - $this->get('database_write'), 3),
335 'database_write' => round($this->get('database_write'), 3),
336 'cache_read' => round($this->get('cache'), 3),
337 'cache_write' => round($this->get('cache_write'), 3),
338 'network_io' => round($this->get('network'), 2),
339 'file_io' => round($this->get('file'), 2),
340 'other_io' => round($duration - ($this->get('database')
341 + $this->get('cache') + $this->get('cache_write')
342 + $this->get('network') + $this->get('file')), 2),
343 'total' => round($duration, 2)
347 if ($this->isRendertime()) {
348 $output = $this->getRendertimeString();
349 $logger->info($message . ": " . $output, ['action' => 'profiling']);
354 * Finds an entry of the container by its identifier and returns it.
356 * @param string $id Identifier of the entry to look for.
358 * @throws NotFoundExceptionInterface No entry was found for **this** identifier.
359 * @throws ContainerExceptionInterface Error while retrieving the entry.
363 public function get(string $id): int
365 if (!$this->has($id)) {
368 return $this->performance[$id];
372 public function set($timestamp, string $id)
374 $this->performance[$id] = $timestamp;
378 * Returns true if the container can return an entry for the given identifier.
379 * Returns false otherwise.
381 * `has($id)` returning true does not mean that `get($id)` will not throw an exception.
382 * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
384 * @param string $id Identifier of the entry to look for.
388 public function has(string $id): bool
390 return isset($this->performance[$id]);