Get query execution time in laravel apps; In this tutorial, we are going to talk about how to get query execution time in laravel 10, 9, 8, 7 apps.
When developing a Laravel application, it can be useful to measure the time taken to execute a particular database query. Measuring query execution time can help us identify performance bottlenecks in our application and optimize our queries for better performance. In this article, we will discuss how to get the query execution time in Laravel.
How to Get Query Execution Time in Laravel
Using the given below simple methods that you can use to get the query execution time in your Laravel application:
- Method 1: Using Laravel’s query log
- Method 2: Using the
DB::select
method
Method 1: Using Laravel’s query log
Laravel’s query log records all queries executed by the application, along with their execution time. We can use this log to retrieve the execution time of a particular query.
To enable the query log, we can set the DB_QUERY_LOG
environment variable to true
in our .env
file.
DB_QUERY_LOG=true
Once the query log is enabled, we can retrieve the execution time of a particular query as follows:
use Illuminate\Support\Facades\DB;
DB::enableQueryLog();
// Execute the query
$results = DB::table('users')->get();
// Get the query log
$queryLog = DB::getQueryLog();
// Get the last query and its execution time
$lastQuery = end($queryLog);
$executionTime = $lastQuery['time'];
echo "Execution time: {$executionTime} ms";
In this code, we first enable the query log using the enableQueryLog
method on the DB
facade. We then execute the query and retrieve the query log using the getQueryLog
method. We access the last element of the query log using the end
function and retrieve the execution time of the query from the time
attribute of the query log.
Method 2: Using the DB::select
method
We can use Laravel’s DB::select
method to execute a raw SQL query and retrieve its execution time.
use Illuminate\Support\Facades\DB;
// Get the current timestamp
$start = microtime(true);
// Execute the query
$results = DB::select("SELECT * FROM users");
// Get the execution time
$executionTime = microtime(true) - $start;
echo "Execution time: {$executionTime} ms";
In this code, we first retrieve the current timestamp using the microtime
function. We then execute the query using the DB::select
method and retrieve the execution time by subtracting the start timestamp from the current timestamp.
Conclusion
Measuring the execution time of a database query is an essential tool for optimizing the performance of our Laravel application. We can retrieve the execution time using Laravel’s query log or by executing a raw SQL query using the DB::select
method. By measuring query execution time, we can identify performance bottlenecks in our application and optimize our queries for better performance.