在關鍵程式碼段落插入計時點,記錄微秒時間與標籤,最後統計相鄰兩點差值,輸出或寫入日誌,快速找出耗時區塊。
<?php
// 全域計時器 ID
$_timer_id = 0;
/**
* 記錄計時點
* @param string $notes 標籤 (建議含 __LINE__)
* @param bool $onOff 開關,正式環境可設 false 關閉
*/
function makeTimer($notes, $onOff = FALSE) {
if ($onOff) {
global $_timer_id;
$GLOBALS['timer'][$_timer_id][0] = microtime(TRUE);
$GLOBALS['timer'][$_timer_id][1] = $notes;
$_timer_id++;
}
}
/**
* 輸出所有區間耗時
* @return string 格式化報表
*/
function traceTimer() {
$timer_str = '';
$G_timer = count($GLOBALS['timer']) - 1;
if ($G_timer > 0) {
for ($i = 0; $i < $G_timer; $i++) {
$dif = number_format($GLOBALS['timer'][$i+1][0] - $GLOBALS['timer'][$i][0], 3);
$timer_str .= "dif: {$dif} {$GLOBALS['timer'][$i][1]}\n";
}
// 最後一點到現在
$dif = number_format(microtime(TRUE) - $GLOBALS['timer'][$G_timer][0], 3);
$timer_str .= "dif: {$dif} {$GLOBALS['timer'][$G_timer][1]}\n";
}
return $timer_str;
}
?>
<?php
// 開啟計時
makeTimer(' LINE:' . __LINE__, true);
$imgstrpos = strpos($str, '<img' . $imgstr);
makeTimer(' LINE:' . __LINE__, true);
$str_p = substr($str_noimg, 0, $imgstrpos);
makeTimer(' LINE:' . __LINE__, true);
$str_n = substr($str_noimg, $imgstrpos, strlen($str_noimg));
makeTimer(' LINE:' . __LINE__, true);
$pst_exc_imgs = $str_p . '<img ' . $imgstr . '>' . $str_n . " ";
makeTimer(' LINE:' . __LINE__, true);
// 輸出或記錄
error_log(traceTimer(), 3, '/tmp/' . basename(__FILE__) . '.log');
// 或直接 echo traceTimer();
?>
dif: 0.001 LINE:12 dif: 0.003 LINE:14 dif: 0.000 LINE:16 dif: 0.002 LINE:18 dif: 0.001 LINE:20
memory_get_usage())。auto_prepend_file / auto_append_file 全站無侵入式植入。