2015-08-15 20 views
1

我只想端口從C++到PHP代碼,但這個循環需要用C 200毫秒+ +,但在PHP12秒如何加快通過PHP中的數組循環?

$answers2 = array_fill(0,28124*2+1,false); 
$answers = SplFixedArray::fromArray($answers2); 
for($i=0;$i< count($abundants);$i++){ 
    for($j=0;$j<=$i;$j++){ 
      $answers[$abundants[$i]+$abundants[$j]]=true; 
    } 
} 

原單C++代碼

#include <iostream> 
#include <vector> 

using namespace std; 

int sum_of_divisors(int n){ 
    int prod=1; 
    for(int k=2;k*k<=n;++k){ 
    int p=1; 
    while(n%k==0){ 
     p=p*k+1; 
     n/=k; 
    } 
    prod*=p; 
    } 
    if(n>1) 
    prod*=1+n; 
    return prod; 
} 

int main(){ 
    vector<int> abundant; 

    for(int i=2;i<=28123;++i) 
    if(sum_of_divisors(i)>2*i) 
     abundant.push_back(i); 

    bool sum_of_abundants[28123*2+1]={false}; 

    for(int i=0;i<abundant.size();++i) 
    for(int j=0;j<=i;++j) 
     sum_of_abundants[abundant[i]+abundant[j]]=true; 

    int sum=0; 

    for(int i=1;i<30000;++i) 
    if(!sum_of_abundants[i]) 
     sum+=i; 

    cout << sum << endl; 
} 

完整的PHP代碼

<?php 
function is_abundant($num){ 
    $sum = 1; 
    for($i = 2 ; $i <= sqrt($num) ; $i++){ 
     if($num % $i == 0){ 
      if($i!=$num/$i){ 
       $sum += $i + $num/$i; 
      } 
      else{ 
       $sum+= $i; 
      } 
      if($sum > $num){ 
       return true; 
      } 
     } 
    } 
} 
$abundants = new SplFixedArray(6965); 
//init 
$index = 0; 
for($j = 0 ;$j < 28124 ; $j++){ 
    if(is_abundant($j)){ 
     $abundants[$index] = $j; 
     $index++; 
    } 
} 
$answers2 = array_fill(0,28124*2+1,false); 
$answers = SplFixedArray::fromArray($answers2); 

$times = microtime(true); 
for($i=0;$i< count($abundants);$i++){ 
    for($j=0;$j<=$i;$j++){ 
      $answers[$abundants[$i]+$abundants[$j]]=true; 
    } 
} 
echo microtime(true) - $times."\n"; 

$sum = 0; 
for($i = 0 ;$i < 28124 ; $i++){ 
    if(!$answers[$i]) 
     $sum+=$i; 
} 
echo $sum."\n"; 

我使用php版本5.5.9-1ubuntu4.11。 你能幫我解決這個問題嗎?

回答

1

請嘗試執行以下操作。您在每次迭代中都會調用count方法,這是性能問題。只要使用一次,計數值分配給一個變量count

$count = count($abundants); 
for($i=0 ; $i<$count ; $i++){ 
    for($j=0;$j<=$i;$j++){ 
      $answers[$abundants[$i]+$abundants[$j]]=true; 
    } 
} 

你會發現循環優化的廣泛的名單here

謝謝:)

+0

謝謝,但仍然有同樣的問題! – Daniyal

+0

另一個原因是PHP的動態輸入。這裏,變量類型在運行時進行檢查,而不是編譯時間,這會影響PHP的運行時性能。因此,像C++這樣的靜態類型語言在運行時會顯着加快速度,儘管它們通常需要提前編譯。 –

+2

'++ $ i'也比'$ i ++'快大約25%,因爲在後者中,變量在遞增之前被臨時緩存。用於長時間迭代。 – jonbaldie