¿Cuántas veces has escrito $start = microtime(true) para medir cuánto tarda algo? Laravel tiene una forma más elegante: Benchmark::measure().
Compatibilidad
Laravel: 9.32+
PHP: 8.0+
Uso básico
<?php
use Illuminate\Support\Benchmark;
$time = Benchmark::measure(fn () => User::all());
echo $time; // 12.345 (milisegundos)Olvídate de esto:
<?php
// ❌ La forma antigua
$start = microtime(true);
$users = User::all();
$time = (microtime(true) - $start) * 1000;Medir múltiples operaciones
Pasa un array para comparar alternativas:
<?php
use Illuminate\Support\Benchmark;
$times = Benchmark::measure([
'eloquent' => fn () => User::all(),
'query' => fn () => DB::table('users')->get(),
'raw' => fn () => DB::select('SELECT * FROM users'),
]);
// [
// 'eloquent' => 15.234,
// 'query' => 8.456,
// 'raw' => 5.123,
// ]Múltiples iteraciones
El segundo parámetro ejecuta el código N veces y devuelve el promedio:
<?php
use Illuminate\Support\Benchmark;
// Ejecutar 100 veces y promediar
$average = Benchmark::measure(
fn () => Str::slug('Hola Mundo'),
iterations: 100
);Útil para operaciones muy rápidas donde una sola medición no es representativa.
Benchmark::dd()
Para debug rápido, imprime el resultado y termina la ejecución:
<?php
use Illuminate\Support\Benchmark;
Benchmark::dd(fn () => $this->heavyOperation());
// 234.567msCon múltiples operaciones:
<?php
use Illuminate\Support\Benchmark;
Benchmark::dd([
'con cache' => fn () => Cache::remember('users', 60, fn () => User::all()),
'sin cache' => fn () => User::all(),
]);
// con cache: 0.123ms
// sin cache: 15.456msCasos de uso prácticos
Comparar estrategias de consulta
<?php
use Illuminate\Support\Benchmark;
$times = Benchmark::measure([
'whereIn' => fn () => Product::whereIn('category_id', $ids)->get(),
'each' => fn () => collect($ids)->map(fn ($id) => Product::where('category_id', $id)->get())->flatten(),
], iterations: 10);
logger('Query comparison', $times);Evaluar impacto de eager loading
<?php
use Illuminate\Support\Benchmark;
Benchmark::dd([
'lazy' => fn () => Order::all()->each(fn ($o) => $o->user->name),
'eager' => fn () => Order::with('user')->get()->each(fn ($o) => $o->user->name),
], iterations: 5);Medir serialización
<?php
use Illuminate\Support\Benchmark;
$data = User::with('posts', 'comments')->get();
Benchmark::dd([
'toArray' => fn () => $data->toArray(),
'toJson' => fn () => $data->toJson(),
'serialize' => fn () => serialize($data),
]);En comandos Artisan
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Benchmark;
class OptimizeImportCommand extends Command
{
protected $signature = 'import:benchmark';
public function handle(): int
{
$times = Benchmark::measure([
'chunk' => fn () => $this->importWithChunk(),
'lazy' => fn () => $this->importWithLazy(),
'cursor' => fn () => $this->importWithCursor(),
]);
foreach ($times as $method => $ms) {
$this->line("{$method}: {$ms}ms");
}
return self::SUCCESS;
}
}Benchmark en tests
Útil para asegurar que una operación no supere cierto tiempo:
<?php
namespace Tests\Feature;
use Illuminate\Support\Benchmark;
use Tests\TestCase;
class PerformanceTest extends TestCase
{
public function test_search_responds_under_100ms(): void
{
Product::factory()->count(1000)->create();
$time = Benchmark::measure(
fn () => Product::search('test')->get(),
iterations: 5
);
$this->assertLessThan(100, $time, "Search tardó {$time}ms");
}
}value() para obtener el resultado
Si necesitas el resultado además del tiempo, usa value():
<?php
use Illuminate\Support\Benchmark;
[$result, $time] = Benchmark::value(fn () => User::all());
echo "Tardó {$time}ms en cargar {$result->count()} usuarios";Consideraciones
No uses en producción
Benchmark añade overhead. Úsalo solo en desarrollo o tests:
<?php
use Illuminate\Support\Benchmark;
if (app()->environment('local')) {
Benchmark::dd(fn () => $this->operation());
}Cuidado con el cache
La primera ejecución suele ser más lenta:
<?php
use Illuminate\Support\Benchmark;
// Primera ejecución: incluye conexión a BD, cache frío, etc.
// Usa iteraciones para obtener un promedio más realista
$time = Benchmark::measure(fn () => User::all(), iterations: 10);Conclusión
Benchmark::measure() elimina el boilerplate de medir rendimiento. Compara queries, evalúa estrategias y detecta cuellos de botella sin ensuciar tu código con microtime().
Curso Laravel 12
Completo 2026
El único curso 100% actualizado que incluye Laravel 12, Livewire 3, Vue 3, React 19 e Inertia 2. Aprende con proyectos reales y las últimas funcionalidades.
star Incluido en cualquier suscripción