timer_stop()
Retrieve or display the time from the page start to when function is called.
No Hooks.
Return
String
. The "second.microsecond" finished time calculation. The number is formatted for human consumption, both localized and rounded.
Usage
timer_stop( $display, $precision );
- $display(int|true|false)
- Whether to echo or return the results. Accepts 0|false for return,
1|true for echo.
Default: 0|false - $precision(int)
- The number of digits from the right of the decimal to display.
Default: 3
Examples
#1 Demonstration of work
echo 'Seconds: '. timer_stop( 0 ); // Seconds: 0.098 echo 'Seconds: '. timer_stop( 0, 5 ); // Seconds: 0.09774 echo 'Seconds: '. timer_stop( 0, 10 ); // Seconds: 0.0977458954
Several calls:
echo timer_stop( 0 ); // Seconds: 0.055 sleep( 1 ); echo timer_stop( 0 ); // Seconds: 1,055
#2 Let's measure how much time elapsed before the main part of the WP kernel is loaded
if( isset( $_GET['check_time'] ) ){ add_filter( 'init', function(){ echo timer_stop( 0, 6 ); // print: 0.002664 exit; }, PHP_INT_MAX ); } /* Go to the URL http://site/?check_time and see: 0.035360 */
#3 Let's measure the time it takes to generate a WordPress page
To do this, call the function at the very end of the page, with the wp_footer hook:
add_action( 'wp_footer', function(){ echo 'Seconds to generate page: '. timer_stop( 0, 4 ); } ); // Seconds to generate page: 0.1066
#4 Print the generation time of the page, the number of requests and how much memory was used
Display it all in the footer of the site (in the front) and in the footer of the admin panel:
// Outputs data about the number of queries to the database, the script execution time // and the amount of memory consumed. add_action('admin_footer_text', 'wp_usage' ); // in the footer of the admin add_action( 'wp_footer', 'wp_usage' ); // in the footer of the site function wp_usage(){ echo sprintf( 'SQL: %d in %s sec. %s MB', get_num_queries(), timer_stop( 0, 3 ), round( memory_get_peak_usage()/1024/1024, 2 ) ); }
Notes
- Global. float. $timestart Seconds from when timer_start() is called.
- Global. float. $timeend Seconds from when function is called.
Changelog
Since 0.71 | Introduced. |
timer_stop() timer stop code WP 6.7.1
function timer_stop( $display = 0, $precision = 3 ) { global $timestart, $timeend; $timeend = microtime( true ); $timetotal = $timeend - $timestart; if ( function_exists( 'number_format_i18n' ) ) { $r = number_format_i18n( $timetotal, $precision ); } else { $r = number_format( $timetotal, $precision ); } if ( $display ) { echo $r; } return $r; }