Skip to main content
Login Join
Snippet · PHP

Measure Any Custom Database Query Execution Time

Shared by Yasha mehta · July 14, 2026

4 views
Back to Snippets

How it works:

* Records the current timestamp before running the query.
* Executes the database query using `$wpdb->get_results()`.
* Calculates the elapsed time immediately after the query completes.
* Logs the execution time to the PHP error log.

This technique is useful for:

* Identifying slow SQL queries.
* Comparing the performance of different query implementations.
* Debugging performance bottlenecks during plugin or theme development.
* Benchmarking custom database operations.

global $wpdb;

$start = microtime( true );

$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE post_status = %s", 'publish' ) );

$execution_time = microtime( true ) - $start;

error_log( sprintf( 'Database query took %.5f seconds.', $execution_time ) );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments