2012-04-11 5 views
3

이 코드를 더 빠르게 최적화 할 수있는 방법이 있습니까? 나는 어떤 제안을 주시면 감사하겠습니다!PHP의 코드 루프 최적화

이 코드는 그래프를 만드는 동안 가장자리를 처리합니다. 변수의

foreach($times_arrival as $city_id => $time_points) { 
// if city is not prohibited for transfers and there is and exists any departure times for this city 
if (isset($times_departure[$city_id]) && isset($cities[$city_id])) 
{ 
    foreach($times_arrival[$city_id] as $t1_info) 
    { 
     foreach($times_departure[$city_id] as $t2_info) 
     { 
      if ($t1_info[0] != $t2_info[0]) //transfers are allowed only for different passages 
      { 
       $t1 = $t1_info[1]; 
       $t2 = $t2_info[1]; 

       $vertex_key = new Vertex($city_id, $t1, 1); 
       $vertex_key = $vertex_key->toString(); 

       //minimum transfer time is 10 min. 
       if (date('H:i', strtotime($t2)) > date('H:i', strtotime('+ 10 minutes', strtotime($t1)))) 
       { 
        $this->graph[$vertex_key][] = new Edge(
         NULL, 
         $vertex_key, 
         new Vertex($city_id, $t2, 0), 
         (float) 0, 
         $f((strtotime($t2) - strtotime($t1))/60, 0, 1) //edge weight 
        ); 
       } 
       //if transfer is on the bound of the twenty-four hours 
       else if (date('H:i', strtotime('+ 24 hours', strtotime($t2))) > date('H:i', strtotime('+ 10 minutes', strtotime($t1)))) 
       { 
        $this->graph[$vertex_key][] = new Edge(
         NULL, 
         $vertex_key, 
         new Vertex($city_id, $t2, 0), 
         (float) 0, 
         $f(strtotime('+ 24 hours', strtotime($t2)) - strtotime($t1)/60, 0, 1) //edge weight 
        ); 
       } 
      } 
     } 
    } 
} 
} 

예 :이 경우

var_dump($times_arrival); //$times_departure have the same structure 
array 
    3 => 
    array 
     0 => 
     array 
      0 => string '1' (length=1) 
      1 => string '08:12' (length=5) 
     1 => 
     array 
      0 => string '2' (length=1) 
      1 => string '08:40' (length=5) 
    41 => 
    array 
     0 => 
     array 
      0 => string '21' (length=2) 
      1 => string '12:40' (length=5) 
+0

와우! 'foreach (foreach (foreach ($ foo => $ bar)))' –

+1

일부'$ times_arrival' 데이터를 게시하십시오. –

+0

@GabrielSantos가 업데이트되었습니다. – Yekver

답변

0

감사합니다. 속도가 느린 이유는 기능이 strtotime()date() 인 것입니다.

-1

는 당신이 좋은 또는 나쁜 알고리즘을 선택했는지 여부 말할 수있다. 내 관점에서 귀하의 코드에 여분의 계산이 없습니다.

하나의 권장 사항 - 가능한 경우 Xdebug를 사용하여 코드를 프로파일 링하고 병목 현상이 발생한 위치를 찾으십시오.

+0

적어도 노드에서 전처리를 할 수 있으므로 O (n^3) ~ O (n^2) 또는 O (nlogn)에 따라 예상되는 big-O가 낮아질 수 있습니다. 그가 정확히 무엇을해야하는지에 관해서. –

+0

이제는 O (n^2)가 n^3이 아니므로 O (nlogn)로 축소 할 수도 있고 그렇지 않을 수도 있습니다. 그러나 수학을 깨끗하게하는 것은 아닙니다. 프로그램과 가능한 것은 궁극적으로 알고리즘 최적화가 아닌 코드 최적화를 통해 가속화 될 수 있습니다. – user1303559

+0

기술적으로 O (m * n^2)입니다. 여기서 n은 도착 배열의 길이이고 m은 출발 배열의 길이입니다. 중첩 된 for-loops가 세 개 있기 때문에이를 알 수 있습니다. 데이터 입력에 대한 설명을 게시 할 수 있다면이를 알고리즘 방식으로 빠르게 수행 할 수 있습니다. –