PHPackages                             methorz/php-profiler - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. methorz/php-profiler

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

methorz/php-profiler
====================

Request-scoped performance profiling with detailed timing, memory tracking, percentile metrics, and intelligent threshold monitoring for PHP applications

v1.0.1(5mo ago)00MITPHPPHP ^8.2CI passing

Since Dec 10Pushed 5mo agoCompare

[ Source](https://github.com/MethorZ/php-profiler)[ Packagist](https://packagist.org/packages/methorz/php-profiler)[ RSS](/packages/methorz-php-profiler/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (4)Used By (0)

PHP Profiler
============

[](#php-profiler)

[![CI](https://github.com/methorz/php-profiler/workflows/CI/badge.svg)](https://github.com/methorz/php-profiler/actions)[![codecov](https://camo.githubusercontent.com/bf6444b7634effee3d18ff283a3795d104420e62488b0aeb9b559374a628f4c0/68747470733a2f2f636f6465636f762e696f2f67682f6d6574686f727a2f7068702d70726f66696c65722f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/methorz/php-profiler)[![PHPStan](https://camo.githubusercontent.com/3d63a7e6e05ca0dafbdd1cb2da881539a5ccd543deb25f6d8d1174cd11815bfe/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c2532306d61782d627269676874677265656e2e7376673f7374796c653d666c6174)](https://phpstan.org/)[![PHP Version](https://camo.githubusercontent.com/c9f64f714c636ba27a3bba6dfd52f98426832db1262747efa54b212d16943651/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c7565)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

Request-scoped performance profiling library for PHP with detailed timing breakdowns, memory tracking, percentile metrics, and intelligent threshold monitoring.

Features
--------

[](#features)

- ⏱️ **Precise Timing** - Microsecond-precision operation timing with checkpoint support
- 💾 **Memory Profiling** - Track current, peak, and delta memory usage
- 📊 **Percentile Metrics** - P50, P75, P90, P95, P99 for statistical analysis
- 📈 **Comparative Analysis** - Before/after comparisons for optimization measurement
- 🎲 **Sampling Mode** - Reduce overhead with configurable sampling rates
- ⚠️ **Smart Thresholds** - Configurable warnings for slow operations and high memory
- 🔧 **Context-Aware** - Automatic configuration based on environment
- 💿 **Persistent Storage** - Store metrics for later analysis
- 🗄️ **Query Analysis** - MySQL EXPLAIN integration for slow queries
- 🎯 **Zero Production Overhead** - Can be completely disabled
- 🔌 **Easy Integration** - Simple trait for repository/service integration
- 📝 **Multiple Formats** - Console-friendly and JSON output

Installation
------------

[](#installation)

```
composer require methorz/php-profiler
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use MethorZ\Profiler\OperationProfiler;

$profiler = OperationProfiler::start('database_query');

$profiler->checkpoint('prep');
$params = $this->prepareParams($data);

$profiler->checkpoint('exec');
$result = $this->executeQuery($query, $params);

$profiler->checkpoint('hydrate');
$objects = $this->hydrate($result);

$metrics = $profiler->end();
```

### Repository Integration

[](#repository-integration)

```
use MethorZ\Profiler\Concern\ProfilesOperations;

class UserRepository
{
    use ProfilesOperations;

    public function fetchUsers(array $ids): array
    {
        $profiler = $this->startProfiling('fetch_users');

        try {
            $profiler->checkpoint('prep');
            $query = $this->buildQuery($ids);

            $profiler->checkpoint('exec');
            $result = $this->dal->execute($query);

            $profiler->checkpoint('hydrate');
            $users = $this->hydrate($result);

            $profiler->addCount('rows', count($users));
            return $users;
        } finally {
            $profiler->end();
        }
    }

    public function getLastQueryMetrics(): array
    {
        return $this->getLastProfilingMetrics();
    }
}
```

Advanced Features
-----------------

[](#advanced-features)

### 1. Context-Aware Profiling

[](#1-context-aware-profiling)

Automatically adjusts behavior based on environment:

```
use MethorZ\Profiler\ContextAwareProfiler;

// Auto-detects environment and configures appropriately
$profiler = ContextAwareProfiler::create();
$opProfiler = $profiler->start('operation');

// Production web: disabled
// Production CLI: 10% sampling
// Development: full profiling
```

### 2. Sampling Mode (Production Use)

[](#2-sampling-mode-production-use)

Profile only a percentage of operations:

```
use MethorZ\Profiler\SamplingProfiler;

$sampler = new SamplingProfiler(0.1); // 10% sampling
$profiler = $sampler->start('high_traffic_operation');
// ... operation
$metrics = $profiler->end();
```

### 3. Percentile Metrics

[](#3-percentile-metrics)

Statistical analysis of operation performance:

```
use MethorZ\Profiler\MetricsCollector;

$collector = new MetricsCollector();

foreach ($batches as $batch) {
    $profiler = OperationProfiler::start('batch_process');
    // ... process batch
    $metrics = $profiler->end();
    $collector->record('batch_process', $metrics);
}

$aggregate = $collector->aggregate();
// Returns: ['percentiles' => ['p50' => 0.05, 'p95' => 0.15, 'p99' => 0.25, ...]]
```

### 4. Comparative Analysis

[](#4-comparative-analysis)

Measure optimization impact:

```
use MethorZ\Profiler\Analysis\MetricsComparator;
use MethorZ\Profiler\Storage\FileStorage;

$storage = new FileStorage('./metrics');

// Before optimization
$profiler = OperationProfiler::start('slow_query');
$result = $this->oldImplementation();
$before = $profiler->end();
$storage->store('before', $before);

// After optimization
$profiler = OperationProfiler::start('slow_query');
$result = $this->newImplementation();
$after = $profiler->end();

$comparator = new MetricsComparator();
$comparison = $comparator->compare($before, $after);

// Returns detailed comparison with improvement/regression detection
echo $comparison['summary']['messages'][0];
// "Performance improvement: 43.2% faster (0.5s → 0.284s)"
```

### 5. Persistent Storage

[](#5-persistent-storage)

Store metrics for later analysis:

```
use MethorZ\Profiler\Storage\FileStorage;

$storage = new FileStorage('./profiling-data');

$profiler = OperationProfiler::start('operation');
// ... operation
$metrics = $profiler->end();

// Store metrics
$storage->store('optimization_v1', $metrics);

// Retrieve later
$historical = $storage->retrieve('optimization_v1');
```

### 6. MySQL Query Analysis

[](#6-mysql-query-analysis)

Automatic EXPLAIN for slow queries:

```
use MethorZ\Profiler\Database\MysqlQueryExplainer;

$explainer = new MysqlQueryExplainer($pdo);

$profiler = OperationProfiler::start('complex_query');
$result = $this->executeQuery($query);
$metrics = $profiler->end();

if ($metrics['total'] > 1.0) { // Slow query
    $explain = $explainer->explain($query);

    if ($explainer->needsOptimization($explain)) {
        $suggestions = $explainer->getSuggestions($explain);
        // ['Full table scan on "users" - consider adding an index']
    }
}
```

### 7. Performance Monitoring with Thresholds

[](#7-performance-monitoring-with-thresholds)

Automatic warnings for performance issues:

```
use MethorZ\Profiler\PerformanceMonitor;

$monitor = PerformanceMonitor::create()
    ->setSlowOperationThreshold(1.0)    // 1 second
    ->setSlowPhaseThreshold(0.5)        // 500ms
    ->setHighMemoryThreshold(0.7)       // 70% of memory limit
    ->setHighRowCountThreshold(10000);  // 10k rows

$profiler = OperationProfiler::start('operation', $monitor);
// ... operation
$metrics = $profiler->end();

// Metrics include warnings if thresholds exceeded
if (isset($metrics['context']['warnings'])) {
    foreach ($metrics['context']['warnings'] as $warning) {
        error_log($warning);
    }
}
```

Output Formatting
-----------------

[](#output-formatting)

### Console Output

[](#console-output)

```
use MethorZ\Profiler\Formatter\ConsoleFormatter;

$formatter = new ConsoleFormatter();
echo $formatter->format($metrics);
```

Output:

```
Operation: fetch_users
Total: 125.50ms
Phases:
  prep:      3.20ms (2.5%)
  exec:    100.10ms (79.7%)
  hydrate:  22.20ms (17.7%)
Memory: 45.2MB (peak: 48.7MB, Δ+3.5MB)
Counts: ids: 150, rows: 2340

```

### JSON Export

[](#json-export)

```
use MethorZ\Profiler\Formatter\JsonFormatter;

$formatter = new JsonFormatter(prettyPrint: true);
$json = $formatter->format($metrics);
file_put_contents('metrics.json', $json);
```

Configuration
-------------

[](#configuration)

### Disable Profiling (Production)

[](#disable-profiling-production)

```
// Disable globally (zero overhead)
OperationProfiler::setEnabled(false);
```

### Environment-Based Configuration

[](#environment-based-configuration)

```
// .env file
APP_ENV=production  // Auto-disables for web, samples for CLI

// Override in code
$profiler = ContextAwareProfiler::create()
    ->forceEnable()  // Force enabled regardless of environment
    ->forceSamplingRate(0.05);  // 5% sampling
```

Best Practices
--------------

[](#best-practices)

### ✅ DO

[](#-do)

- Profile at repository/port layer for database operations
- Use checkpoints to identify bottlenecks within operations
- Aggregate metrics for batch operations
- Use sampling mode in production
- Store metrics for trend analysis
- Compare before/after for optimization verification

### ❌ DON'T

[](#-dont)

- Profile every method call (too much overhead)
- Use for production monitoring without sampling (use proper APM tools)
- Store metrics in database (they're request-scoped)
- Profile trivial operations (&lt;1ms)
- Forget to disable in production web requests

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- ext-json

Testing
-------

[](#testing)

```
# Run tests
composer test

# Run tests with coverage
composer test-coverage

# Run all quality checks
composer check
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Comparison to Other Tools
-------------------------

[](#comparison-to-other-tools)

Featurephp-profilerOpenTelemetryPrometheusStatsD**Purpose**Dev profilingDistributed tracingTime-series metricsReal-time metrics**Overhead**Medium (dev)Low (sampling)LowVery low**Memory tracking**✅ Yes❌ No❌ No❌ No**Percentiles**✅ Yes✅ Yes✅ Yes⚠️ Limited**Sub-operations**✅ Checkpoints✅ Spans⚠️ Manual⚠️ Manual**Comparison**✅ Built-in❌ No❌ No❌ No**Production**⚠️ Sampling only✅ Yes✅ Yes✅ Yes**Setup**✅ Simple⚠️ Medium✅ Simple✅ Simple**Use php-profiler for:** Development profiling, optimization measurement, debugging performance issues

**Use OpenTelemetry/Prometheus for:** Production monitoring, distributed tracing, long-term metrics storage

Credits
-------

[](#credits)

Created by [Thorsten Merz](https://github.com/methorz)

Links
-----

[](#links)

- [GitHub Repository](https://github.com/methorz/php-profiler)
- [Packagist](https://packagist.org/packages/methorz/php-profiler)
- [Documentation](https://github.com/methorz/php-profiler/wiki)
- [Issue Tracker](https://github.com/methorz/php-profiler/issues)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance73

Regular maintenance activity

Popularity0

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

2

Last Release

155d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b0233a9072fdc1746031fd96b487fce9b0d5f55c0124b70fc51ac2bb833bb906?d=identicon)[MethorZ](/maintainers/MethorZ)

---

Tags

analyticsbenchmarkingdebuggingdeveloper-toolsinstrumentationmemory-profilingmetricsmonitoringobservabilityoptimizationpercentilesperformanceperformance-monitoringphpphp8profilerprofilingrequest-profilingsamplingtimingmonitoringperformanceprofilingMetricsmemorybenchmarkingoptimizationtiming

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/methorz-php-profiler/health.svg)

```
[![Health](https://phpackages.com/badges/methorz-php-profiler/health.svg)](https://phpackages.com/packages/methorz-php-profiler)
```

###  Alternatives

[phpbench/phpbench

PHP Benchmarking Framework

2.0k13.0M627](/packages/phpbench-phpbench)[ekino/newrelic-bundle

Integrate New Relic into Symfony2

28111.2M8](/packages/ekino-newrelic-bundle)[jackwh/laravel-new-relic

Monitor your Laravel application performance with New Relic

112827.2k](/packages/jackwh-laravel-new-relic)[slickdeals/statsd

a PHP client for statsd

264.5M8](/packages/slickdeals-statsd)[scoutapp/scout-apm-laravel

Scout Application Performance Monitoring Agent - https://scoutapm.com

23831.3k](/packages/scoutapp-scout-apm-laravel)[tomloprod/time-warden

TimeWarden is a lightweight PHP library that enables you to monitor the processing time of tasks and task groups (useful during the development stage). Additionally, it allows you to set maximum execution times to tasks, empowering proactive actions when tasks exceed their planned duration.

16916.2k](/packages/tomloprod-time-warden)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
