<?php
function calculate($period) {
return cos(time() % $period);
}
$start = time();
$value = 0;
for ($i = 0; $i < 2000; $i++) {
$value += calculate(360);
}
$finish = time();
echo "執行時間: " . ($finish - $start) . " 秒\n";
echo "value = $value\n";
?>
time():每次迴圈呼叫 calculate() 內部又呼叫 time(),系統呼叫開銷可避免。time() 秒級精度,短時間執行易為 0 秒;應用 microtime(true) 或 hrtime()。<?php
// 1. 將 time() 提至迴圈外
$now = time();
$period = 360;
$value = 0;
$start = microtime(true);
for ($i = 0; $i < 2000; $i++) {
$value += cos($now % $period);
}
$elapsed = microtime(true) - $start;
echo "優化後執行時間: " . number_format($elapsed * 1000, 3) . " ms\n";
echo "value = $value\n";
?>
將函數邏輯直接寫在迴圈內,消除呼叫開銷:
for ($i = 0; $i < 2000; $i++) {
$value += cos($now % 360);
}
若函數內有昂貴初始化,用 static 避免重複:
function heavyCalc($x) {
static $cache = [];
if (!isset($cache[$x])) {
$cache[$x] = expensive_operation($x);
}
return $cache[$x];
}
若輸入域有限 (如 $period 固定),預先建立對應表:
$cosTable = [];
for ($i = 0; $i < 360; $i++) {
$cosTable[$i] = cos($i);
}
for ($i = 0; $i < 2000; $i++) {
$value += $cosTable[$now % 360];
}
大量數學運算可考慮 FFI 呼叫 C 庫、或安裝 php-math、NumPHP 等擴展。
<?php
function bench($name, callable $fn, $iterations = 10000) {
$start = hrtime(true);
for ($i = 0; $i < $iterations; $i++) $fn();
$ns = hrtime(true) - $start;
echo "$name: " . number_format($ns / $iterations / 1e6, 3) . " ms/iter\n";
}
$now = time();
bench('原版函數呼叫', fn() => cos($now % 360));
bench('內聯運算', fn() => cos($now % 360)); // 實際相同,示意
bench('查表法', function() use ($now) {
static $t = null;
$t ??= array_map('cos', range(0, 359));
return $t[$now % 360];
});
?>
microtime(true) 或 hrtime() 進行精確測量,避免 time() 秒級誤差。