Download the PHP package bakame/aide-profiler without Composer
On this page you can find all versions of the php package bakame/aide-profiler. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download bakame/aide-profiler
More information about bakame/aide-profiler
Files in bakame/aide-profiler
Package aide-profiler
Short Description A minimalist, embeddable, multi-metric, and framework-agnostic profiler for PHP
License MIT
Informations about the package aide-profiler
Aide Profiler
A minimalist profiler for PHP. The profiler is embeddable, multi-metric, and framework-agnostic It fills the gap between a basic timer and full-blown profilers like Xdebug or Blackfire.
Installation
composer require bakame/aide-profiler
You need PHP >= 8.1 but the latest stable version of PHP is recommended
Usage
Traditionally, profiling a section of code quickly looks like this:
The Bakame\Aide\Profiler
package streamlines this process by
removing the need for manual timing and setup, making
profiling more convenient and consistent.
Profiler
Metrics quick access
Let's adapt the first example using the Profiler
class.
`
They are as many static methods as they are metrics:
Profiler::executionTime()
;Profiler::cpuTime()
;Profiler::memoryUsage()
;Profiler::peakMemoryUsage()
;Profiler::realMemoryUsage()
;Profiler::realPeakMemoryUsage()
;
If you want to access all the metrics at once, you can use the following method
Profiler::metrics()
;
The method returns a Metrics
class with readonly methods for each metric.
`
All duration values are expressed in nanoseconds, while memory-related metrics are measured in bytes.
You can retrieve the Metrics
statistics in a human-readable format using the Metrics::forHuman()
method.
You can either:
- Call the method without arguments to retrieve all metrics as formatted strings in an associative
array
. - Or pass the name of a specific metric to retrieve only that value, formatted for human readability.
Iterations
To calculate the average usage of a specific metric, specify the number of iterations as the second argument. The callback will be executed accordingly, and the method will return the average value over all iterations:
The
$iterations` argument is available for all metrics.
Accessing the result
Finally, the static method Profiler::execute
allows you to retrieve both the result of a callback
execution and its profiling data. It returns a ProfiledResult
instance, where the result
property contains the callback’s return value, and the summary
property holds the
profiling metrics collected during the call.
`
Metrics recording
Beyond its static methods, the Profiler
also supports recording multiple individual calls.
To enable this, create a new Profiler
instance by passing in the callback you wish to profile.
`
You can execute the Profiler
instance as many times as needed — it will record all
execution metrics each time.
You can access any Summary
by index using the nth
method, or use the first
and latest
methods
to quickly retrieve the first and last recorded Summary
. The nth
method also accepts negative
integers to simplify access from the end of the list.
Using labels
To add a custom label to each run, use Profiler::profile
. This method works like the
run
method but allows you to assign a custom label to the returned Summary
object
via its first argument.
`
You can reuse the same label multiple times. The Profiler::get()
method returns the most recent
entry associated with the specified label. In contrast, Profiler::getAll()
returns an array
of all entries recorded under that label, ordered from oldest to newest.
If the label is invalid or has never been used, Profiler::getAll()
returns an empty array
while Profiler::get()
returns null
. To determine whether a label exists, use Profiler::has()
,
which returns true
if the label has been recorded, or false
otherwise.
Resetting the Profiler
At any given time you can reset the Profiler
by clearing all the Summary
already recorded.
[!NOTE]
PHP provides areset_peak_memory_usage
that will globally reset all peak memory usage data.
Marker
In situation where you can't work with callbacks you can alternatively use the Marker
class.
The Marker
class profiles across labeled checkpoints ("snapshots") in your
code. You can start a new Marker
using the static method:
Taking Snapshots
Use mark()
to mark significant points in your code:
Each label must be unique. Labels are automatically normalized (e.g., trimmed, validated).
Getting profiling results`
To get a high-level profile between the first and lastest snapshot use the summarize
method.
You can provide a custom label for the summary:
If needed, you can measure the profiling data between two specific labels:
Or you can iterate over each successive pair of snapshots to return the consecutive deltas:
Finalizing the marker
To end profiling and automatically take the last snapshot and return the summary:
Just like with the summary
method you can provide an optional custom label for the summary report:
[!WARNING]
Even though thefinish
calls returns a summary, it does not close the instance. You can still call themark
method and add more snapshots after a call tofinish
. Thesummary
is calculated at runtime and never stored in theMarker
instance.
Marker completion
The complete
method finalizes the profiling marker, marking it as complete and preventing any
further snapshots or finishing operations that modify the state.
Before calling complete
, the marker is open and can accept snapshots via mark
and be finished via finish
. Once complete
is called:
- The marker becomes complete and is closed to further modifications.
- Further calls to
mark
orfinish
will throw anUnableToProfile
exception. - Calling
complete
multiple times has no effects - it is idempotent. - The result of
summary
remains unchanged after completion and can be safely called multiple times.
At any given time you can check your Marker
completion status using the Marker::isComplete
method which returns true
when it is complete; false otherwise.
Marker utility methods
The Marker
instance also gives you access to other utility methods:
[!IMPORTANT]
Thereset()
method reopens the marker and clears all recorded snapshots, enabling it to be reused for a new profiling session.
As an example, you can do the following:
Identifier
Every Marker
and Profiler
instance has a unique identifier accessible via the identifier
method.
If not provided, an internal label generator (e.g. Label::random()
) will assign a unique name to the
property. The identifier can be used for logging, debugging or for correlation when multiple profilers
and/or markers are running in parallel.
Logging
The Profiler
and Marker
classes can optionally log profiling activity using any logger that
implements Psr\Log\LoggerInterface
.
To enable this feature, you must install and configure a PSR-3
-compatible logger. Common
implementations include Monolog
, Laminas\Log
, Symfony’s or Laravel logger
component, and others.
[!TIP]
Logging can be done also on theProfiler
static methods, they all optionally accept aLoggerInterface
argument. When logging marker or profiler instance their respective identifier is added to the log to ease identifying which instance is generating the log entries.
Exporters
The package can help with exporting its metrics using different mechanisms.
JSON
Both the Profiler
and Marker
classes support JSON export via PHP's json_encode
function.
This allows you to serialize profiling data for inspection, storage, or transmission.
Calling json_encode($profiler)
will produce a JSON object containing:
identifier
: the profiler's unique identifiersummaries
: an array of summary entries, ordered from oldest to latest
Each summary entry includes:
label
: the associated label or name of the profiling blocksnapshots
: an array of two snapshots (start and end), ordered chronologicallymetrics
: computed performance metrics between the two snapshots
See a sample profiler JSON output for a complete structure.
Calling json_encode($marker)
will produce a JSON object containing:
identifier
: the marker's unique identifiersnapshots
: an array of snapshot entries, ordered from oldest to latest
See a sample marker JSON output for a complete structure.
CLI
If you have the symfony\console
package installed in your application, you can export
the Profiler
or the Marker
using a table showing all the data recorded by
each instance using the ConsoleTableExporter
class.
the following table will be outputted in your terminal.
Open Telemetry
The Profiler
and the Marker
results can be exported to an Open telemetry compatible
server using the open-telemetry/exporter-otlp
package.
To do so, first install the package if it is not yet the case, then do the following:
Remember to change the $tracerProvider
to connect to your own environment and server.
Helpers
Environment
The package includes an Environment
class that collects information about the current system for profiling purposes.
Apart from returning raw information about your system, the instance can be used to detect the PHP architecture used or if the memory is unlimited using boolean returning methods:
`
The ConsoleTableExporter
also provides an exporter for the class:
Will return
MemoryUnit and DurationUnit
To correctly show the memory and duration unit, the package comes with 2 helper Enum:
MemoryUnit
to help formatting and converting to and from bytes.DurationUnit
to help formatting and converting to and from nanoseconds.
Testing
The library has:
- a PHPUnit test suite.
- a coding style compliance test suite using PHP CS Fixer.
- a code analysis compliance test suite using PHPStan.
To run the tests, run the following command from the project folder.
Contributing
Contributions are welcome and will be fully credited. Please see CONDUCT for details.
Security
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
Changelog
Please see CHANGELOG for more information on what has changed recently.