Measure How Long Code Takes
Adds wpide_timer_start() and wpide_timer_stop() helpers that measure the time and memory a piece of code uses and write the result to the PHP error log, to find slow functions.
Opens WPIDE on
Code
if ( ! function_exists( 'wpide_timer_start' ) ) {
function wpide_timer_start( $name ) {
$GLOBALS['wpide_timers'][ $name ] = array( microtime( true ), memory_get_usage() );
}
function wpide_timer_stop( $name, $log = true ) {
if ( empty( $GLOBALS['wpide_timers'][ $name ] ) ) {
return null;
}
list( $started, $memory ) = $GLOBALS['wpide_timers'][ $name ];
unset( $GLOBALS['wpide_timers'][ $name ] );
$ms = round( ( microtime( true ) - $started ) * 1000, 2 );
if ( $log ) {
error_log( sprintf( '[timer] %s: %s ms, %s memory', $name, $ms, size_format( max( 0, memory_get_usage() - $memory ), 1 ) ) );
}
return $ms;
}
}
Notes
Example wpide_timer_start( 'menu' ); ... wpide_timer_stop( 'menu' ); the stop call also returns the milliseconds.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.