farjadtahir / perfscope
Zero dependency PHP performance profiler for timing spans, database queries, memory and micro benchmarks. Works in any PHP project or framework.
Requires
- php: ^8.4
Requires (Dev)
- laravel/pint: ^1.0
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^12.0 || ^13.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-30 14:35:09 UTC
README
A free, zero dependency performance profiler for PHP. Time any piece of code, watch your database queries, track memory, benchmark alternatives, and get a readable report with plain language hints about what to fix.
It works in any PHP project: plain PHP, Laravel, Symfony, WordPress, Slim, CodeIgniter, or your own framework. Requires PHP 8.4 or newer, and is built for PHP 8.4, 8.5 and 8.6.
Why I built this
This is the tool I reach for most when I profile the performance of applications, especially ones that are already finished and live, when it is time to optimise them. At that stage I do not want a heavy setup or a paid service. I want to wrap the parts I suspect, run a few real requests, and see where the time goes.
I am sharing it for free so any developer can drop it into any PHP project and use it the same way. If it saves you an afternoon of guessing, it has done its job.
Farjad Tahir
What you get
- Timing spans. Wrap any code in a named span. Spans nest, and every span reports its total time and its self time (the time spent in that span alone, without its children). Self time is the number you actually optimise.
- Database query tracking. Record queries from any source and get slow query lists, combined query time, and automatic detection of repeated queries, which is the classic N+1 problem.
- Memory and CPU. Memory change per span, peak memory, CPU user and system time, garbage collector activity and the number of files loaded.
- An advisor. Plain language notes such as "Xdebug is active, so these timings are inflated", "OPcache is off", or "this query ran 40 times".
- Four report formats. Text for terminals and logs, JSON for tools, HTML for a visual waterfall, and a Server Timing header so numbers appear in your browser developer tools.
- Micro benchmarks. Compare two ways of doing the same job with mean, median, 95th percentile and operations per second.
- Safe by default. Off unless you switch it on, never throws into your application, and capped so it cannot use unbounded memory.
- No dependencies. Just PHP.
What it is not
Perfscope is an instrumentation profiler. You decide which parts of the code to measure and it reports exactly those parts, with very little overhead. That makes it ideal for finding which layer of an application is slow (routing, database, templates, an external API) and for checking that a fix really helped.
It is not a call graph profiler. It will not tell you which individual function inside a span is the hot one. When you need that level of detail, use a tool such as XHProf, Excimer, SPX, Blackfire or Xdebug profiling on the span that Perfscope pointed you to. The two approaches work well together: Perfscope finds the slow area quickly, and a call graph profiler explains it.
Requirements
- PHP 8.4 or newer. The test suite is configured to run on PHP 8.4, 8.5 and 8.6.
- Optional: the
mbstringextension (used to avoid cutting multibyte characters in half) andpdo_sqlite(only needed to run the database tests and example).
Installation
composer require farjadtahir/perfscope
To use it only on a development or staging machine, add it as a development dependency instead:
composer require --dev farjadtahir/perfscope
You can also copy the src folder into your project and load it with any PSR 4 autoloader using the namespace Perfscope\.
Quick start
<?php use Perfscope\Config; use Perfscope\Profiler; use Perfscope\Reporter\TextReporter; require __DIR__ . '/vendor/autoload.php'; $profiler = new Profiler(new Config()); $profiler->start('handle request', 'http'); // measure() runs your code, times it, and returns whatever it returns. $products = $profiler->measure('load products', fn () => $repository->all(), 'db'); // Or open and close a span yourself. $profiler->start('render page', 'view'); $html = $template->render($products); $profiler->stop('render page'); $profiler->stop('handle request'); echo (new TextReporter())->render($profiler->finish());
The second argument of start() and measure() is a category. Categories group spans in the summary, so "db", "http", "view" or "cache" shows you at a glance which layer is expensive.
Run the bundled examples to see real output:
php examples/basic.php php examples/database.php php examples/benchmark.php
Turning it on safely
There are two ways to create a configuration, and they behave differently on purpose.
new Config() is enabled. Use it when you decide in code exactly when profiling happens, for example inside a test or a script.
Config::fromEnvironment() is disabled unless you switch it on. It reads PERFSCOPE_ENABLED from the environment, and only a truthy value (1, true, yes, on) turns profiling on. Use it when the profiler is part of the code you deploy, so a forgotten call can never slow down production.
use Perfscope\Config; use Perfscope\Perfscope; Perfscope::boot(Config::fromEnvironment());
Then enable it only where you want it, for example in a staging environment file or for one process:
PERFSCOPE_ENABLED=1 php artisan queue:work
When profiling is disabled, every call returns immediately. measure() still runs your callback, so leaving the calls in your code changes nothing about how it behaves.
The shared profiler (static shortcut)
If passing a profiler object around is awkward, use the Perfscope class. It keeps one shared profiler, so any file can add a span:
use Perfscope\Config; use Perfscope\Perfscope; use Perfscope\Sink\FileSink; // Once, as early as possible in your entry point. Perfscope::boot(Config::fromEnvironment()); Perfscope::register(new FileSink(__DIR__ . '/var/perfscope.jsonl')); // Anywhere else. Perfscope::start('checkout'); Perfscope::measure('charge card', fn () => $gateway->charge($order), 'http'); Perfscope::stop('checkout');
register() writes the finished report to your sinks automatically when the script ends. If a sink fails, the error goes to your PHP error log and the response is never affected.
Core ideas
Spans are stretches of work with a start and an end. They nest. If a span starts while another is open, it becomes its child.
Self time is a span's total time minus the time of its direct children. A parent span can look slow only because its children are slow. Look at self time to find the code that actually needs fixing.
Marks are single points on the timeline, such as "routes loaded". Use them when you care about when something happened rather than how long it took.
Queries are tracked separately from spans. Anything that can report an SQL string and a duration can feed them in, and each query remembers which span was open when it ran.
The report is what finish() returns: spans, marks, queries, an environment snapshot and the advisor notes. Reporters turn it into text, JSON or HTML, and sinks decide where it goes.
If you forget to stop a span, Perfscope closes it for you when you stop its parent or finish the profile, and flags it as auto closed, so one mistake cannot corrupt the whole timeline.
Reading a report
This is real output from examples/basic.php (abridged, and your numbers will differ):
================================================================================
PERFSCOPE REPORT
================================================================================
Target basic.php
Total time 75.30 ms
Before profiler 0.91 ms
Peak memory 701.69 KB
CPU time 16.85 ms user, 14.94 ms system
Files loaded 16
TIMELINE
share total self span
[############] 74.81 ms 0.99 ms handle request (http)
[#...........] 8.18 ms 8.18 ms load configuration (io)
[##########..] 65.64 ms 0.07 ms build page (view)
[#...........] 6.16 ms 6.16 ms render header (view)
[#########...] 55.20 ms 55.20 ms render products (view)
[#...........] 4.21 ms 4.21 ms render footer (view)
[............] 0.49 ms 0.49 ms (outside every span)
TIME BY CATEGORY (self time)
view 65.64 ms 87.2% 4 spans
io 8.18 ms 10.9% 1 span
http 0.99 ms 1.3% 1 span
TOP SPANS BY SELF TIME
55.20 ms render products
8.18 ms load configuration
6.16 ms render header
4.21 ms render footer
0.99 ms handle request
DATABASE QUERIES
1 query, 12.40 ms combined
MARKS
8.42 ms configuration ready
THINGS TO CHECK
[INFO] OPcache is off for the command line. Production web requests normally
run with it on, so compile time here can be higher than in production.
[INFO] 3 spans took 40.00 ms or more, parents included. The slowest is "handle
request" at 74.81 ms.
================================================================================
How to read it:
- Before profiler is the time between the request starting and the profiler being created. In a framework this is roughly your boot time.
- build page has a total of 65.64 ms but a self time of only 0.07 ms. It is not the problem. Its child, render products, is.
- (outside every span) is time that no span covers. If this number is large, you have blind spots, and the advisor will say so.
- Things to check are conclusions drawn from the facts in the report, not guesses.
Reports and where they go
A reporter decides how a report looks. A sink decides where it goes. Any reporter works with any sink.
Reporters:
TextReporterfor terminals, logs and tickets. ASCII only.JsonReporterfor machines. Withpretty: falseit prints one line, which makes a log file of JSON Lines thatjqand log tools can read.HtmlReporterfor a visual waterfall. Usenew HtmlReporter(standalone: true)for a full page you can save, or the default to drop a block into a page during development. Everything from your application is escaped.ServerTimingReporterfor the Server Timing header, which browsers show in the Network tab. Callsend($report)before output starts.
Sinks:
FileSinkappends to a file with a lock, so concurrent requests never interleave. The default is one JSON line per report.OutputSinkprints to the screen. It stays silent on web requests unless you passallowWeb: true, so it can never corrupt an API response.CallbackSinkhands the report to your own function, for a logger or a metrics service.
use Perfscope\Reporter\HtmlReporter; use Perfscope\Sink\CallbackSink; use Perfscope\Sink\FileSink; use Perfscope\Sink\OutputSink; Perfscope::register( new FileSink('/var/log/app/perfscope.jsonl'), new FileSink('/var/log/app/last.html', new HtmlReporter(standalone: true)), new CallbackSink(fn ($report) => $logger->info('profile', $report->toArray())), );
Database queries
You have three ways to feed queries in.
1. Raw PDO. Create your connection with ProfiledPdo instead of PDO. It is a real PDO, so nothing else changes, and exec(), query() and prepared statements are all timed.
use Perfscope\Database\ProfiledPdo; $pdo = new ProfiledPdo($dsn, $user, $password, $options, $profiler);
Limits: values passed through bindValue() or bindParam() are not captured, only values given to execute(). It cannot be combined with persistent connections, because PDO does not allow a custom statement class there.
2. Any framework or library that already times queries. Report them yourself:
Perfscope::query($sql, $durationInMilliseconds, $bindings);
The framework guides below show how to connect Laravel and WordPress this way.
3. Time a callback.
$rows = Perfscope::timeQuery('SELECT * FROM orders', fn () => $db->fetchAll(...));
Finding N+1 problems
Perfscope reduces every statement to a fingerprint by removing literal values and ignoring case and spacing, so these two count as the same query:
SELECT * FROM users WHERE id = 4 SELECT * FROM users WHERE id = 9
When one shape runs three or more times (configurable), it appears under "Repeated" in the report, and the advisor warns you. Typical fixes are eager loading, a single query with a join, or an IN list.
Benchmarks
Use the benchmark runner to compare two implementations before you commit to one:
use Perfscope\Benchmark\Benchmark; use Perfscope\Reporter\BenchmarkTextReporter; $results = Benchmark::compare([ 'foreach loop' => fn () => doItWithALoop($data), 'array_map' => fn () => doItWithArrayMap($data), ], iterations: 3_000, warmup: 100); echo (new BenchmarkTextReporter())->render($results);
Results come back fastest first, with mean, median, 95th percentile, maximum, calls per second and how much slower each one is than the fastest.
For trustworthy numbers: warm up first, keep the callback small and free of output, compare the median and the percentiles rather than only the mean, run on the same machine with Xdebug off, and repeat the run a few times.
Framework guides
These are starting points. The Perfscope calls are the same everywhere. Only the place you put them changes. Adjust names and paths to match your application and framework version.
Plain PHP and any other framework
Put this at the top of your entry point (usually public/index.php) and wrap the work your front controller does:
require __DIR__ . '/../vendor/autoload.php'; use Perfscope\Config; use Perfscope\Perfscope; use Perfscope\Sink\FileSink; Perfscope::boot(Config::fromEnvironment()); Perfscope::register(new FileSink(__DIR__ . '/../var/perfscope.jsonl')); Perfscope::start('request', 'http'); // ... run your application ... Perfscope::stop('request');
Keep the report file outside your public web root.
Laravel
Boot the profiler and connect the query listener in AppServiceProvider:
use Illuminate\Database\Events\QueryExecuted; use Illuminate\Support\Facades\DB; use Perfscope\Config; use Perfscope\Perfscope; use Perfscope\Sink\FileSink; public function boot(): void { Perfscope::boot(Config::fromEnvironment()); if (! Perfscope::profiler()->isEnabled()) { return; } Perfscope::register(new FileSink(storage_path('logs/perfscope.jsonl'))); // $query->time is already in milliseconds. DB::listen(static function (QueryExecuted $query): void { Perfscope::query($query->sql, $query->time, $query->bindings); }); }
Wrap each request with a small middleware:
namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Perfscope\Perfscope; use Symfony\Component\HttpFoundation\Response; final class ProfileRequest { public function handle(Request $request, Closure $next): Response { Perfscope::start('laravel request', 'http'); try { return $next($request); } finally { Perfscope::stop('laravel request'); } } }
Register it first in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware) { $middleware->prepend(\App\Http\Middleware\ProfileRequest::class); })
Then set PERFSCOPE_ENABLED=1 in your environment file. The "Before profiler" line in the report shows how long Laravel took to boot before the provider ran.
Symfony
Create an event subscriber. It boots the profiler on the main request and closes the request span when the kernel terminates:
namespace App\EventSubscriber; use Perfscope\Config; use Perfscope\Perfscope; use Perfscope\Sink\FileSink; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\Event\TerminateEvent; use Symfony\Component\HttpKernel\KernelEvents; final class PerfscopeSubscriber implements EventSubscriberInterface { public function __construct( #[Autowire('%kernel.project_dir%')] private readonly string $projectDir, ) { } public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['onRequest', 512], KernelEvents::TERMINATE => ['onTerminate', -512], ]; } public function onRequest(RequestEvent $event): void { if (! $event->isMainRequest()) { return; } Perfscope::boot(Config::fromEnvironment()); Perfscope::register(new FileSink($this->projectDir . '/var/log/perfscope.jsonl')); Perfscope::start('symfony request', 'http'); } public function onTerminate(TerminateEvent $event): void { Perfscope::stop('symfony request'); } }
This is written for the classic one request per process model of PHP FPM. For queries, create your DBAL connection through ProfiledPdo where you can, or report queries from a DBAL logging middleware with Perfscope::query().
WordPress
Create a file in your WordPress must use plugins folder, for example perfscope.php, and install Perfscope somewhere it can be loaded. To capture queries, add define('SAVEQUERIES', true); to your WordPress main config file.
<?php /** * Plugin Name: Perfscope Loader * Description: Profiles each request when PERFSCOPE_ENABLED is set. */ use Perfscope\Config; use Perfscope\Perfscope; use Perfscope\Sink\FileSink; // Adjust to wherever you ran "composer require". require_once dirname(ABSPATH) . '/perfscope/vendor/autoload.php'; $config = Config::fromEnvironment(); if (! $config->enabled) { return; } Perfscope::boot($config); Perfscope::start('wordpress request', 'http'); add_action('shutdown', static function (): void { global $wpdb; Perfscope::stop('wordpress request'); // Each entry is [sql, seconds, caller, ...]. foreach ((array) ($wpdb->queries ?? []) as $query) { Perfscope::query((string) $query[0], (float) $query[1] * 1000.0); } // Written outside the web root so it cannot be downloaded. (new FileSink(dirname(ABSPATH) . '/perfscope.jsonl'))->write(Perfscope::finish()); }, PHP_INT_MAX);
Switch it on for a request or for the site by setting the environment variable in your server configuration, or with putenv('PERFSCOPE_ENABLED=1'); near the top of your WordPress main config file.
A profiling workflow for finished applications
This is the routine I follow when an application is live or nearly live and needs to be faster.
- Make the conditions honest. Turn Xdebug off, use OPcache like production does, and use realistic data. The advisor warns you about the common mistakes.
- Measure a baseline. Wrap the request end to end, run the slow page or job several times, and note the median total time, not the best run.
- Read the advisor first. Repeated queries and slow queries are the most common wins and need no further digging.
- Follow self time. Open "Top spans by self time". The first entry is where to look. If most of the time is outside every span, add spans around bootstrap, routing and rendering until the blind spot is small.
- Split the winner. Add child spans inside the slowest span to find which part of it is slow. Repeat until the cause is obvious.
- Use a call graph profiler if you need to. When one small span still hides the problem, run XHProf, Excimer or Xdebug on just that span.
- Change one thing, then measure again. Compare against the baseline using the same data. Keep the JSON reports so you can show before and after numbers in a pull request.
Configuration reference
Pass these as named arguments to new Config(...).
enabled(defaulttrue). When false, every call is a cheap no op.slowSpanMs(default100.0). Spans at or above this are listed as slow.slowQueryMs(default50.0). Queries at or above this are listed as slow.duplicateQueryThreshold(default3). How many times one query shape must repeat before it is flagged.captureBindings(defaultfalse). Store bound parameter values. Off by default because they can contain personal data.maxSqlLength(default2000). Longest SQL text kept per query, in bytes.maxSpans(default10000) andmaxQueries(default5000). Safety caps. Anything beyond them is counted and reported as dropped instead of stored.strict(defaultfalse). Throw aProfilerExceptionon misuse, such as stopping a span that was never started. Useful in tests.
Environment variables read by Config::fromEnvironment(): PERFSCOPE_ENABLED, PERFSCOPE_SLOW_SPAN_MS, PERFSCOPE_SLOW_QUERY_MS, PERFSCOPE_DUPLICATE_THRESHOLD and PERFSCOPE_CAPTURE_BINDINGS. Invalid values fall back to the defaults instead of raising an error.
Overhead and accuracy
Each span costs two reads of a monotonic clock, two memory readings and one small object. That is negligible next to work measured in milliseconds, but it is not free, so:
- Wrap meaningful units of work, not the inside of a tight loop. Thousands of tiny spans cost more than they tell you, and the
maxSpanscap will start dropping them. - Time uses PHP's
hrtime(), which is monotonic and unaffected by clock changes. - Xdebug slows PHP a great deal. Perfscope detects it and warns you, but the right fix is to switch it off while you profile.
- To measure the overhead on your own hardware, use the benchmark runner on a start and stop pair.
$result = Benchmark::run(function () use ($profiler): void { $profiler->start('probe'); $profiler->stop('probe'); }, iterations: 5_000);
Security and privacy
A profile describes your application, so treat the output like a log file.
- Off by default when you use
Config::fromEnvironment(). - Bound values are not stored unless you enable
captureBindings. - SQL text is stored. If your code puts personal data directly into SQL strings instead of using prepared statements, that data will appear in reports. Profile on staging or on anonymised data in that case.
- Only the request path is stored, never the query string, because query strings often carry tokens and email addresses. Paths can still contain identifiers, so keep reports private.
- Do not expose reports. Write them outside your public web root. Send the Server Timing header and the HTML report only in development, on staging, or to authenticated staff.
- The HTML report escapes all values from your application, but it uses a style element. If your Content Security Policy forbids inline styles, write the report to a file with
FileSinkinstead.
If you find a security problem, please open a private security advisory on the GitHub repository rather than a public issue.
Development
composer install composer test # PHPUnit composer analyse # PHPStan at the maximum level composer style # check code style (Laravel Pint, PER preset) composer style:fix # fix code style composer check # all of the above
The tests use a fake clock, so every timing assertion is exact and never flaky. GitHub Actions runs the style check, static analysis and the test suite on PHP 8.4, 8.5 and 8.6.
Contributing
Bug reports, ideas and pull requests are welcome. Please run composer check before you open a pull request, and add a test for any behaviour you change.
Licence
MIT. See the LICENSE file. Free to use in personal and commercial projects.
Author
Built and shared by Farjad Tahir. If you use it and it helps, a star on the repository is a nice way to say so.
Support
Perfscope is free and always will be. If it saved you time and you would like to support its upkeep, you can buy me a coffee.