微时间的正确使用
Correct use of microtime
我正在尝试使用 microtime()
比较两个函数。
但是,我得到了意想不到的结果。
根据我对这个 SO post (Tracking the script execution time in PHP) 的理解,我应该能够从 $after
中减去 $before
以获得以秒为单位的执行时间。
我的脚本是这样设置的:
<?php
$int = 4;
$before = microtime(true);
print_r(filter_var($int, FILTER_VALIDATE_INT));
echo '<br />';
$after = microtime(true);
echo ($after - $before). 'sec' ."\n";
echo '<br />';
$int = 4;
$before = microtime(true);
print_r(is_int($int));
echo '<br />';
$after = microtime(true);
echo ($after - $before) .'sec' ."\n";
我知道这不是执行时间的准确迭代,因为它不会将函数循环 X 次以获得平均值 - 首先只是进行基本测试,所以请忽略这方面。
当我在浏览器中转到此页面时,我得到以下输出:
4
9.0599060058594E-6sec
1
9.5367431640625E-7sec
页面加载时间不到一秒 - 为什么会出现 9.XYZ
让我有点困惑。
我使用 microtime()
正确吗?附带问题:如何查看哪个函数最快?链接问题中接受的答案为两个函数输出了 0 毫秒。
编辑
我将脚本更改为:
<?php
function checkInt($int)
{
return is_int($int);
}
function checkIntFilter($int)
{
return filter_var($int, FILTER_VALIDATE_INT);
}
$before = microtime(true);
for ($i = 1; $i < 1000; $i++)
{
checkInt(4);
}
$after = microtime(true);
echo ($after - $before). ' sec' .'<br />';
$before = microtime(true);
for ($i = 1; $i < 1000; $i++)
{
checkIntFilter(4);
}
$after = microtime(true);
echo ($after - $before). ' sec';
现在输出:
7.1048736572266E-5 sec
0.00024008750915527 sec
然而,我的页面肯定在 7 秒内加载 - 第二个结果看起来是正确的,但我不确定第一个......
您没有正确阅读结果。那就是“scientific notation”,用来表示值太小或太大不方便处理。
7.1048736572266E-5
秒等于 0.000071048736572266
秒。
所以你是对的,你的测试确实花费了比 7 秒少得多的时间。
我正在尝试使用 microtime()
比较两个函数。
但是,我得到了意想不到的结果。
根据我对这个 SO post (Tracking the script execution time in PHP) 的理解,我应该能够从 $after
中减去 $before
以获得以秒为单位的执行时间。
我的脚本是这样设置的:
<?php
$int = 4;
$before = microtime(true);
print_r(filter_var($int, FILTER_VALIDATE_INT));
echo '<br />';
$after = microtime(true);
echo ($after - $before). 'sec' ."\n";
echo '<br />';
$int = 4;
$before = microtime(true);
print_r(is_int($int));
echo '<br />';
$after = microtime(true);
echo ($after - $before) .'sec' ."\n";
我知道这不是执行时间的准确迭代,因为它不会将函数循环 X 次以获得平均值 - 首先只是进行基本测试,所以请忽略这方面。
当我在浏览器中转到此页面时,我得到以下输出:
4
9.0599060058594E-6sec
1
9.5367431640625E-7sec
页面加载时间不到一秒 - 为什么会出现 9.XYZ
让我有点困惑。
我使用 microtime()
正确吗?附带问题:如何查看哪个函数最快?链接问题中接受的答案为两个函数输出了 0 毫秒。
编辑
我将脚本更改为:
<?php
function checkInt($int)
{
return is_int($int);
}
function checkIntFilter($int)
{
return filter_var($int, FILTER_VALIDATE_INT);
}
$before = microtime(true);
for ($i = 1; $i < 1000; $i++)
{
checkInt(4);
}
$after = microtime(true);
echo ($after - $before). ' sec' .'<br />';
$before = microtime(true);
for ($i = 1; $i < 1000; $i++)
{
checkIntFilter(4);
}
$after = microtime(true);
echo ($after - $before). ' sec';
现在输出:
7.1048736572266E-5 sec
0.00024008750915527 sec
然而,我的页面肯定在 7 秒内加载 - 第二个结果看起来是正确的,但我不确定第一个......
您没有正确阅读结果。那就是“scientific notation”,用来表示值太小或太大不方便处理。
7.1048736572266E-5
秒等于 0.000071048736572266
秒。
所以你是对的,你的测试确实花费了比 7 秒少得多的时间。