2012-04-11 27 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

だけあなたが良いか悪いかのアルゴリズムを選択したかどうかを言うことができます。私の視点では、あなたのコードに余分な計算はありません。

1つの推奨事項 - Xdebugを使用してコードをプロファイリングし、可能であればボトルネックがどこにあるかを調べる。

+0

少なくとも彼は自分のノードで前処理を行うことができるでしょう。これは期待されるbig-Oを〜O(n^3)からO(n^2)、おそらくO(nlogn)に下げます正確に彼は何をしなければならないのか。 –

+0

これはO(n^2)がn^3ではなく、可能な限りO(nlogn)に減らすかどうか、そして、あなたは「正確に彼が何をしなければならないかによって」と言います。しかし、それはクリーンな数学ではありません - そのプログラムと可能性は、最終的にはアルゴリズムを最適化することによってスピードアップする可能性があります。 – user1303559

+0

技術的にはO(m * n^2)です.nは到着配列の長さ、mは出発配列の長さです。 3つのネストされたfor-loopsがあるので、これを知っています。彼がデータ入力についての説明を投稿できるのであれば、これを行うためにアルゴリズム的に速い方法があることを保証します。 –