Test query execution time in laravel

Test query execution time in laravel

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Benchmarking Query Performance in Laravel Without External Dependencies

When profiling application performance, developers often reach for external tools like Blackfire or Neos Swoft to isolate database latency from other system variables. However, there are scenarios where you need a lightweight solution that runs directly within your existing test suite without installing new dependencies or changing your environment. Laravel provides a built-in mechanism via the Carbon facade and PHPUnit's assertLessThan assertions to measure query execution time directly in code.

The core concept relies on capturing the current timestamp immediately before executing a database operation and again immediately after. The difference between these two values represents the total duration of the query, including any transaction overhead if you are wrapping the call in a transaction. This approach ensures that the measurement is intrinsic to the application logic rather than dependent on external monitoring agents or specific server configurations.

To implement this, start by recording the starting time using Carbon::now() or the native microtime(true) function for higher precision. Execute your Eloquent query or raw SQL statement. Then, record the ending time. Subtract the start value from the end value to get the elapsed time in microseconds.

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

$startTime = microtime(true);

// Perform your database operation
$model = DB::table('users')->where('status', 'active')->first();

$endTime = microtime(true);
$queryDuration = ($endTime - $startTime) * 1000; // Convert to milliseconds

In a PHPUnit testing context, you typically want to assert that this duration falls below a specific threshold. This prevents regressions where a previously optimized query suddenly slows down due to a database index change or a logic error in a SELECT clause.

public function test_active_users_query_is_fast()
{
    $startTime = microtime(true);
    
    $user = DB::table('users')->where('status', 'active')->first();
    
    $endTime = microtime(true);
    $duration = ($endTime - $startTime) * 1000;

    // Assert the query took less than 5 milliseconds
    $this->assertLessThan(5, $duration, 'Query execution exceeded 5ms threshold');
}

One critical trade-off to consider is the precision of the measurement. While microtime(true) offers microsecond resolution, the overhead of recording timestamps in PHP itself is non-zero. If your query takes only a few microseconds, the noise from timestamp recording might skew your results. For high-precision benchmarking within tight loops, you might need to run the operation multiple times and average the result, though this adds complexity.

Another important distinction is that this method measures wall-clock time, not CPU time. This includes any waiting for I/O, network calls (if using a remote database), or concurrency issues in your application server. If you are testing on a shared hosting environment or a container with resource limits, the measured time will reflect these external constraints. To isolate pure query performance, ensure your tests run against an in-memory SQLite database or a dedicated test instance where other processes aren't competing for resources.

You can also leverage Laravel's DB::listen() method to capture query logs, though this is generally more useful for debugging than high-frequency benchmarking due to the serialization overhead of logging every statement. For strict performance assertions, the manual timestamp approach remains the most direct and dependency-free solution available within the framework.

Our network