ציטוט:
נכתב במקור על ידי Kfir.G
למה צריך פונקציה מוכנה בשביל זה?
PHP קוד:
function getWords ($str, $num, $separator = ' ') {
$count = 0;
$len = strlen($str);
$i = 0;
for(; $i < $len && $count < $num; $i++) {
if($str[$i] == $separator)
$count++;
}
return substr($str,0,$i);
}
|
כי הפיתרון שהבאת איטי... הוא לוקח פי 2 זמן בבדיקה שביצעתי...
קוד:
0.60995697975159 seconds for getWords1($str, 5)
1.2931590080261 seconds for getWords2($str, 5)
PHP קוד:
<?php
ini_set("max_execution_time", 100);
$str = "While I was walking under the BIG brown tree I saw a cat";
function getWords1($str, $num, $seperator = ' ')
{
return implode($seperator, array_slice(explode($seperator, $str), 0, $num));
}
function getWords2 ($str, $num, $separator = ' ')
{
$count = 0;
$len = strlen($str);
$i = 0;
for(; $i < $len && $count < $num; $i++) {
if ($str[$i] == $separator)
$count++;
}
return substr($str, 0, $i);
}
$max = 100000;
$start = microtime(true);
$i = 0;
while ($i < $max) {
getWords1($str, 5);
$i++;
}
$end = microtime(true);
echo ($end - $start) . " seconds for getWords1(\$str, 5)<br />";
sleep(5); //Just in case
$start = microtime(true);
$i = 0;
while ($i < $max) {
getWords2($str, 5);
$i++;
}
$end = microtime(true);
echo ($end - $start) . " seconds for getWords2(\$str, 5)<br />";
?>