Optimization question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Optimization question

Post by Roja »

Design goals:

- Roughly 3000 sectors on average ($_POST['sektors']).
- Average number of links range from 6-10 ($_POST['linksper']).
- Average number of two-way warp links range from 10-40% ($_POST['twoways'])
- The links need to be random
- Sectors *cannot* contain more than $maxlinks in a sector (not done currently)
- Execution time needs to be under 30 seconds for 3000 sectors.

The problem we are facing is that the loops are not optimal, and while db access is fast, adding another db call (a select to check number of links to/from a sector) pushes us WAY beyond the 30 second time.

So, can anyone suggest alternative ways to do this that might be more optimal - speed wise? The current code (below) executes in roughly 27 seconds.

I'm more than willing to recode the db schema as well if you can think of a better way to express one-way/two-way links that will make this faster.

Code: Select all

<?php
      TextFlush("Generating warp links ");    
      for ($i=0; $i<=$_POST['sektors']; $i++)
      {
          $numlinks = mt_rand(0,$_POST['linksper']);
          for ($j=0; $j<$numlinks; $j++)
          {
              $destination = mt_rand(1,$_POST['sektors']);
              if ($destination == $i)
              {
                  $j--;
              }
              else
              {
                 $link_array[]= array ($i, $destination);
                  $link_odds = mt_rand(0,100);
                  if ($link_odds < $_POST['twoways'])
                  {
                        $link_array[]= array ($destination, $i);
                  }
              }
          }
      }

      $debug_query = $db->Execute("INSERT INTO $dbtables[links] (link_start,link_dest) VALUES (?,?)",$link_array);
      db_op_result($debug_query,__LINE__,__FILE__);

?>
Last edited by Roja on Sat Jan 10, 2004 4:04 pm, edited 1 time in total.
jason
Site Admin
Posts: 1767
Joined: Thu Apr 18, 2002 3:14 pm
Location: Montreal, CA
Contact:

Post by jason »

At first glance, you might want to build single, but very large query to run through MySQL, because that seems to be the bottleneck.

Instead of inserting one row at a time, insert them all at once.

http://www.mysql.com/doc/en/INSERT.html
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post by Roja »

Okay, changed to one query (changed original post to reflect new code).

Minor improvement in speed - roughly 2-5%.

Any other suggestions?
Post Reply