0

Measuring memory usage — memory_get_usage, memory_get_peak_usage

Intermediate5 min read·php-15-004
performance

Concept

Blackfire is a commercial PHP profiler built by Sensio (the Symfony team). Unlike Xdebug's Cachegrind output (which must be opened in a desktop app), Blackfire has a web dashboard with call graphs, timeline views, comparison between profiles, and automated performance testing.

How Blackfire works: It uses an instrumentation-based profiler that's significantly lighter than Xdebug. Blackfire uses a probe (PHP extension) + agent (daemon) + companion (browser extension or CLI). Profiling is triggered per-request and doesn't affect other requests or production performance in the same way.

Key Blackfire features:

  • Call graph: Visual tree of function calls with time and memory per node.
  • Timeline: Horizontal timeline showing when each function runs — reveals blocking I/O, sequential database queries, etc.
  • Builds: Profile specific scenarios and compare over time. Detect regressions.
  • Assertions: Write performance budgets in .blackfire.yaml — "API response must be < 200ms", "no more than 30 DB queries". CI integration fails if assertions are violated.
  • Environments: Track performance in staging, detect regressions before production.

Blackfire vs Xdebug: Xdebug is free and shows raw data. Blackfire is paid (free tier available) but gives polished visualization, comparison, and CI integration. For serious performance work, Blackfire is much more productive.

Code Example

yaml
# .blackfire.yaml — performance budget
tests:
  "API response time":
    path: /api/users
    assertions:
      - "main.peak_memory < 30mb"
      - "metrics.sql.queries.count < 10"
      - "main.wall_time < 150ms"

  "No N+1 queries on order list":
    path: /api/orders
    assertions:
      - "metrics.sql.queries.count < 5"
bash
# Install Blackfire CLI
curl -s https://packagecloud.io/gpg.key | sudo apt-key add -
echo "deb http://packages.blackfire.io/debian any main" | sudo tee /etc/apt/sources.list.d/blackfire.list
sudo apt install blackfire blackfire-php

# Configure with your credentials
blackfire config

# Profile a web request
blackfire curl https://app.local/api/orders

# Profile a CLI script
blackfire run php artisan cache:warmup

# Profile with comparison (detect regression)
blackfire run --reference 1 php artisan db:seed  # reference profile
blackfire run --samples 5 php artisan db:seed      # compare 5 samples to reference

# Run assertions in CI
blackfire build-trigger https://app.local --assert-build
php
<?php
// Instrument specific sections with Blackfire SDK
$probe = \BlackfireIo\BlackfireProbe::getMainInstance();

$probe->enable();
// ... code section to profile ...
$probe->disable();

// Add custom probes
$probe->enable('checkout-payment-section');
$this->processPayment($order);
$probe->disable('checkout-payment-section');