简体   繁体   English

如何通过php中的数组加速循环?

[英]How to speed up a loop through an array in php?

I just want to port a code from C++ to php but this loop takes 200ms in C++ but 12 second in php 我只想将代码从C ++移植到php,但是此循环在C ++中需要200毫秒,而在php中需要12秒

$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;
    }
}

Orginal C++ code 原始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;
}

Complete php code 完整的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";

I'm using php version 5.5.9-1ubuntu4.11. 我正在使用php版本5.5.9-1ubuntu4.11。 Could you please help me to fix this issue? 您能帮我解决这个问题吗?

try doing the following. 尝试执行以下操作。 You are calling the count method on every iteration which is a performance hit. 您会在每次迭代中调用count方法,这会对性能造成影响。 Just use it once and assign the count value to a variable count 只需使用一次并将计数值分配给可变count

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

You may find the extensive list of loop optimizations here 您可以在此处找到广泛的循环优化列表

Thank you :) 谢谢 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM