I'm trying to compare two functions using microtime()
.
However, I'm getting unexpected results.
According to my understanding of this SO post (Tracking the script execution time in PHP) I should be able to subtract $before
from $after
to get my execution time in seconds.
I've set my script out like this:
<?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";
I know it's not an accurate iteration of execution time as it doesn't loop the function X times to get an average - just doing a basic test at first, so please ignore that aspect.
When I go to this page in my browser, I get this output:
4
9.0599060058594E-6sec
1
9.5367431640625E-7sec
The page loads in under a second - so why 9.XYZ
is appearing is getting me a little confused.
Am I using microtime()
correctly? Side question: How do I see which function is the fastest? Accepted answer in linked question outputted 0ms for both functions.
edit
I changed my script to this:
<?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';
which now outputs:
7.1048736572266E-5 sec
0.00024008750915527 sec
however, my page definitely loaded in under 7 seconds - the second result looks correct, but I'm not sure about the first ...