Message Boards Message Boards

0
|
7785 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Optimizes for loop with condition?

Posted 7 years ago

How can I optimize and speed the following code?

$T = 99; $y1 = 31; $y2 = 27;
For[$xx = 1, $xx <= 10^3, $xx++,
  Do[$xy = $x1; If[$x1 >= $y1, Break[]];
   $yy = $x1;
   Do[$xy = $x2; If[$x2 >= $y2, Break[]];
    $yy = $x2
    , {$x2, 1, $T}]
   , {$x1, 1, $T}]
  ] // AbsoluteTiming
POSTED BY: Paolo Pellegrini

Well, part of the charm of Mathematica is the possibility of writing "C-like" programs

As a rule of thumb, avoid using "For" loops whenever you can

In your case the for does nothing really, so you may replace it with Do and to speed up, if you have a multicore processor replace the Do with ParallelDo

$T = 99; $y1 = 31; $y2 = 27;
ParallelDo[
  Do[
   $xy = $x1;
   If[$x1 >= $y1,
    Break[]];
   $yy = $x1;
   Do[
    $xy = $x2;
    If[$x2 >= $y2,
     Break[]];
    $yy = $x2,
    {$x2, 1, $T}],
   {$x1, 1, $T}],
  {$xx, 10^3}] // AbsoluteTiming

This speed up thing on my old laptop by factor of 4 BTW, why using $ signs in front of the variables (looks like Pearl). This might cause you problems as many of internal Mathematica constants use this notation.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract