[英]Doubts About PHP Execution Time
I'm trying to measure the time it takes for PHP to sort data using Merge Sort. 我正在尝试测量PHP使用合并排序对数据进行排序所花费的时间。 When I try to sort 10.000+ data, the calculation using
microtime(true)
always returns values like: 当我尝试对10.000+数据进行排序时,使用
microtime(true)
的计算始终返回如下值:
2.8610229492188E-6
4.0531158447266E-6
9.5367431640625E-7
That's not even 1 second. 甚至还不到1秒。 Is PHP really that fast?
PHP真的那么快吗? When I sort the data, I need to wait for a few seconds until the page completely load.
对数据进行排序时,我需要等待几秒钟,直到页面完全加载为止。 Maybe there's something wrong with my code.
也许我的代码有问题。
<?php$fileName = 'Ten_Thousand_Number_List.txt';
$fileContent = file($fileName, FILE_IGNORE_NEW_LINES);
$timeStart = microtime(true);
function mergeSort(&$fileContent) {
if (sizeof($fileContent) <= 1) {
return $fileContent;
}
// Split array into 2, left and right
$leftFrag = array_slice($fileContent, 0, (int)(count($fileContent)/2));
$rightFrag = array_slice($fileContent, (int)(count($fileContent)/2));
// RECURSION
// split the two halves into their respective halves...
$leftFrag = mergeSort($leftFrag);
$rightFrag = mergeSort($rightFrag);
$returnArray = merge($leftFrag, $rightFrag);
return $returnArray;
}
function merge(&$lF, &$rF) {
$result = array();
global $numberOfComparison;
// while both arrays have something in them
while (count($lF)>0 && count($rF)>0) {
if ($lF[0] <= $rF[0]) {
array_push($result, array_shift($lF));
$numberOfComparison++;
}
else {
array_push($result, array_shift($rF));
}
}
// did not see this in the pseudo code,
// but it became necessary as one of the arrays
// can become empty before the other
array_splice($result, count($result), 0, $lF);
array_splice($result, count($result), 0, $rF);
return $result;
}
$timeEnd = microtime(true);
$sortedArray = mergeSort($fileContent);
$memoryAllocation = memory_get_peak_usage();
print_r($sortedArray);
echo "<br>";
// echo "Time elapsed: " . $timeEnd . " " . $timeStart . "<br>";
echo "Time elapsed: " . ($timeEnd - $timeStart) . "<br>";
echo "Memory used: " . $memoryAllocation . "<br>";
?>
You're setting your end time before you've sorted anything. 您要先设置结束时间,然后再对所有内容进行排序。 Change:
更改:
$timeEnd = microtime(true);
$sortedArray = mergeSort($fileContent);
to: 至:
$sortedArray = mergeSort($fileContent);
$timeEnd = microtime(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.