timer_stop()
云策文档标注
概述
timer_stop() 函数用于计算并返回或显示从页面开始加载到函数调用时的执行时间,支持自定义精度和输出方式。
关键要点
- 函数返回或显示页面加载时间,格式为“秒.微秒”,支持本地化和四舍五入。
- 参数 $display 控制输出行为:0 或 false 返回结果,1 或 true 直接输出。
- 参数 $precision 指定小数点后的位数,默认值为 3。
- 内部使用 $timestart 和 $timeend 全局变量计算时间差,优先调用 number_format_i18n() 进行本地化格式化。
代码示例
// 示例1:返回时间并指定精度
echo( 'Seconds: ' . timer_stop( 0 ) . '' );
echo( 'Seconds: ' . timer_stop( 0, 5 ) . '' );
echo( 'Seconds: ' . timer_stop( 0, 10 ) . '' );
// 示例2:在页脚输出加载时间
add_action( 'wp_footer', function() {
echo '' . 'The page is loaded in ' . timer_stop() . ' seconds ';
}, PHP_INT_MAX );
原文内容
Retrieves or displays the time from the page start to when function is called.
Parameters
$displayint|boolrequired-
Whether to echo or return the results. Accepts
0|falsefor return,1|truefor echo. Default0|false. $precisionintoptional-
The number of digits from the right of the decimal to display.
Default:
3
Source
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;
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 3 content
Codex
Determine length of time to render page with a precision of 3, 5 and 10 digits.
echo( 'Seconds: ' . timer_stop( 0 ) . '<br />' ); echo( 'Seconds: ' . timer_stop( 0, 5 ) . '<br />' ); echo( 'Seconds: ' . timer_stop( 0, 10 ) . '<br />' );Output:
Seconds: 0.815 Seconds: 0.81551 Seconds: 0.8155429363Skip to note 4 content
ashour
Check the Pages load Time in seconds
add_action( 'wp_footer', function() { echo '<br/>' . 'The page is loaded in ' . timer_stop() . ' seconds <br/>'; }, PHP_INT_MAX );