2016-12-05 1 views
0

PHPがマージソートを使ってデータをソートするのにかかる時間を測定しようとしています。でも1秒ではありません疑問PHP実行時間について

2.8610229492188E-6 
4.0531158447266E-6 
9.5367431640625E-7 

:私は10.000+データをソートしようとすると、microtime(true)を用いた計算は、常にのような値を返します。 PHPは本当に速いですか?データを並べ替えると、ページが完全に読み込まれるまで数秒間待つ必要があります。多分、私のコードに何か問題があります。

<?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>"; 
?> 

答えて

2

何かを並べ替える前に終了時刻を設定しています。変更:

$timeEnd = microtime(true); 
$sortedArray = mergeSort($fileContent); 

へ:

$sortedArray = mergeSort($fileContent); 
$timeEnd = microtime(true); 
+0

ありがとうございました。私はそれを恋しく思う。 –