note 52486 deleted from function.microtime by tularis
| From: | tularis@php.net | Date: | Sun, 22 Jun 2008 12:14:55 +0000 |
| Subject: | note 52486 deleted from function.microtime by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-140703@lists.php.net to get a copy of this message | ||
Note Submitter: t0russ at gmail dot com
----
<?php
/*
compares runtimes of 2 functions
to use, copy/paste functions, and call them from fct1 and fct2
coded by t0rus
*/
function stripQuotes1($st){
while(($k=strpos($st,'"'))!==false)
$st=substr($st,0,$k).substr($st,$k+1);
while(($k=strpos($st,'\''))!==false)
$st=substr($st,0,$k).substr($st,$k+1);
return $st;
}
function stripQuotes2($str){
for($i=0;$i<strlen($str);$i++)
if (($str{$i}==="'")||($str{$i}==='"')){ // === gave better results
than ==
$str=substr($str,0,$i).substr($str,$i+1);
$i--;
}
return $str;
}
$runtimes=1000;//how many times to run the tests
function fct1(){
stripQuotes1('01abba6"78901\'
1234""12345678\"123-"""3\'\'2');
}
function fct2(){
stripQuotes2('01abba6"78901\'
1234""12345678\"123-"""3\'\'2');
}
//################################################################//
$time1=0;
for ($i=0;$i<$runtimes;$i++){
$time_start = array_sum(explode(' ', microtime()));
fct1();
$time_end = array_sum(explode(' ', microtime()));
$time1 = ($time1*$i+$time_end - $time_start)/($i+1);
}
echo "\nfct1 runs in $time1 ms.\n";
$time2=0;
for ($i=0;$i<$runtimes;$i++){
$time_start = array_sum(explode(' ', microtime()));
fct2();
$time_end = array_sum(explode(' ', microtime()));
$time2 = ($time2*$i+$time_end - $time_start)/($i+1);
}
echo "\nfct2 runs in $time2 ms.\n";
$tf = round($time2/$time1);
echo "\nfct".(($tf>1)?'1 is faster by a factor of '.$tf:(($tf<1)?'2
is faster by a factor of '.round($time1/$time2):'1 is roughly equal to
fct2'))."\n\n";
?>
Sample output:
fct1 runs in 0.00017227101325989 ms.
fct2 runs in 0.0010822315216064 ms.
fct1 is faster by a factor of 6