Audit Site Performance: Query Execution Time

Last updated 1 month ago

PHP
function my_plugin_query_execution_time() {
    global $wpdb;

    // Log query execution time if the site is in debug mode
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        $start_time = microtime( true );
        
        // Hook into database queries and log execution time
        add_filter( 'query', function( $query ) use ( $start_time ) {
            $execution_time = microtime( true ) - $start_time;
            error_log( 'Query Execution Time: ' . $execution_time . 's - ' . $query );
        });
    }
}
add_action( 'wp_footer', 'my_plugin_query_execution_time' );

All code snippets are licensed GPLv2 or later unless otherwise stated.