评估一段 PHP 代码的执行时间:<?php // A function that records the time when it is called function profile($dump = FALSE) { static $profile; // Return the times stored in profile, then erase it if ($dump) { $temp = $profile; unset($profile); return ($temp); } $profile[] = microtime(); }// Set up a tick handler register_tick_function("profile");// Initialize the function before the declare block profile();// Run a block of code, throw a tick every 2nd statement declare(ticks=2) { for ($x = 1; $x < 50; ++$x) { echo similar_text(md5($x), md5($x*$x)), "<br />;"; } }// Display the data stored in the profiler print_r(profile (TRUE)); ?>
// A function that records the time when it is called
function profile($dump = FALSE)
{
static $profile; // Return the times stored in profile, then erase it
if ($dump) {
$temp = $profile;
unset($profile);
return ($temp);
} $profile[] = microtime();
}// Set up a tick handler
register_tick_function("profile");// Initialize the function before the declare block
profile();// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
for ($x = 1; $x < 50; ++$x) {
echo similar_text(md5($x), md5($x*$x)), "<br />;";
}
}// Display the data stored in the profiler
print_r(profile (TRUE));
?>
这个例子评估“declare”中的 PHP 代码,每执行两条低级语句就记录一次时间。此信息可以用来找到一段特定代码中速度慢的部分。这个过程也可以用其它方法完成,但用 tick 更方便也更容易实现。 Ticks 很适合用来做调试,以及实现简单的多任务,后台 I/O 和很多其它任务。