Skip to content

Instantly share code, notes, and snippets.

@ryanjbonnell
Last active May 14, 2017 02:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanjbonnell/5978033 to your computer and use it in GitHub Desktop.
Save ryanjbonnell/5978033 to your computer and use it in GitHub Desktop.
Display WordPress Page Generation Stats for Performance Profiling
<?php
/**
* Display MySQL Query Count and Page Generation Time for Performance Profiling
* ------------------------------------------------------------------------------
*/
if ( ! function_exists( 'show_page_generation_stats' ) ) {
function show_page_generation_stats() {
if ( WP_DEBUG === true && current_user_can('administrator') ) {
global $wpdb;
$query_total = get_num_queries();
$time_total = timer_stop( false, 4 );
$time_mysql = 0;
if ( $wpdb->queries ) {
foreach ( $wpdb->queries as $query ) {
$time_mysql = $time_mysql + $query[1];
}
}
$time_php = $time_total - $time_mysql;
$percentage_mysql = number_format_i18n( $time_mysql / $time_total * 100, 2 );
$percentage_php = number_format_i18n( $time_php / $time_total * 100, 2 );
echo "<!-- $query_total Queries in $time_total Seconds ({$percentage_php}% PHP, {$percentage_mysql}% MySQL) -->\n\n";
}
}
add_action( 'wp_footer', 'show_page_generation_stats', 1001 );
}
?>
@ryanjbonnell
Copy link
Author

For this to work, be sure to have the Save Queries for Analysis constant set in wp-config.php:

define( 'SAVEQUERIES', true );

The SAVEQUERIES definition saves the database queries to an array and that array can be displayed to help analyze those queries. The information saves each query, what function called it, and how long that query took to execute.

Place the code in your theme's footer.php or anywhere you want to see the metrics; the output of the script will be an HTML comment and resemble the following:

<!-- 64 Queries in 0.1311 Seconds (95.38% PHP, 4.62% MySQL) -->

For a more robust solution, the WordPress Debug Bar plugin shows this information and a wealth of other metrics -- highly recommended for theme and plugin developers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment