A simple profiler to measure duration, memory usage and memory peak of various scoped actions.
composer require eliashaeussler/scope-profilerInitialize a new ScopeProfiler\ScopeProfiler instance – either as singleton
if you prefer to use a shared instance or as a new instance if you want to use multiple profilers:
use Eliashaeussler\ScopeProfiler;
// Option A: Shared instance (singleton)
$profiler = ScopeProfiler\ScopeProfiler::get();
// Option B: New instance
$profiler = new ScopeProfiler\ScopeProfiler();To push a new scope, call pushScope() and pass the scope:
$scope = new ScopeProfiler\Scope('Crawling the internet');
$profiler->pushScope($scope);In case the scope should be detached from the profiler instance, simply call pullScope():
$profiler->pullScope($scope);You will receive an instance of ScopeProfiler\Scope which you can use to measure the
duration, memory usage and memory peak of the action. This can either be done automatically by using the
run() method or manually by using the start() and stop() methods:
$task = new SomeLongRunningTask();
// Option A: Automatic start and stop
$result = $scope->run($task->execute(...));
// Option B: Manual start, execute, and stop
$scope->start();
$result = $task->execute();
$scope->stop();You can always profile a scope by measuring the current duration, memory usage and memory peak – either while the scope is still active or after it has finished:
$measurement = $scope->measure();The received object is an instance of ScopeProfiler\Measurement which contains
the following properties:
$duration = $measurement->duration; // float
$memoryUsage = $measurement->memoryUsage; // int
$memoryPeak = $measurement->memoryPeak; // intTo get a nicely formatted string representation of the measurement, call any of the format*() methods:
$formattedMeasurement = $measurement->format(); // Crawling the internet took 7 min and consumed 8 GiB of memory (peak at 16 GiB)
$formattedDuration = $measurement->formatDuration(); // 7 min
$formattedMemoryUsage = $measurement->formatMemoryUsage(); // 8 GiB
$formattedMemoryPeak = $measurement->formatMemoryPeak(); // 16 GiBYou can use the profiler to release all scopes at once:
$scopes = $profiler->releaseScopes();This is especially useful if you want to summarize the results of all scopes at once.
Please have a look at CONTRIBUTING.md.
This project is licensed under GNU General Public License 3.0 (or later).