Skip to content

Instantly share code, notes, and snippets.

@brampta
Forked from Viper007Bond/whatissoslow.php
Last active September 20, 2022 18:02
Show Gist options
  • Save brampta/d2e8ca7dce07156bd2ee294063ebd380 to your computer and use it in GitHub Desktop.
Save brampta/d2e8ca7dce07156bd2ee294063ebd380 to your computer and use it in GitHub Desktop.
WordPress: Times how long it takes each filter and action to run and displays results at the end of the page. Quick and dirty.
<?php
//add this in your theme's functions.php to time all the hooks
// Here's a test to make sure it's working
//add_action( 'wp_footer', function() { sleep( 2 ); } );
class WhatIsSoSlow {
public $data = array();
function __construct() {
add_action( 'all', array( $this, 'filter_start' ) );
add_action( 'shutdown', array( $this, 'results' ) );
}
// This runs first for all actions and filters.
// It starts a timer for this hook.
public function filter_start() {
$current_filter = current_filter();
$this->data[ $current_filter ][]['start'] = microtime( true );
add_filter( $current_filter, array( $this, 'filter_end' ), 99999 );
}
// This runs last (hopefully) for each hook and records the end time.
// This has problems if a hook fires inside of itself since it assumes
// the last entry in the data key for this hook is the matching pair.
public function filter_end( $filter_data=null ) {
$current_filter = current_filter();
remove_filter( $current_filter, array( $this, 'filter_end' ), 99999 );
end( $this->data[ $current_filter ] );
$last_key = key( $this->data[ $current_filter ] );
$this->data[ $current_filter ][ $last_key ]['stop'] = microtime( true );
return $filter_data;
}
// Processes the results and var_dump()'s them. TODO: Debug bar panel?
public function results() {
$results = array();
foreach ( $this->data as $filter => $calls ) {
foreach ( $calls as $call ) {
// Skip filters with no end point (i.e. the hook this function is hooked into)
if ( ! isset( $call['stop'] ) )
continue;
if ( ! isset( $results[ $filter ] ) )
$results[ $filter ] = 0;
$results[ $filter ] = $results[ $filter ] + ( $call['stop'] - $call['start'] );
}
}
asort( $results, SORT_NUMERIC );
$results = array_reverse( $results );
echo '</div></div></div></div><pre style="z-index: 9999;position: relative;background-color: #0ff6;margin-left: 200px;">'.print_r( $results, true ).'</pre>';
}
}
new WhatIsSoSlow();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment