2
$\begingroup$

The two pieces of code below are functionally equivalent, and I would have expected similar performance. (The only difference between the two is the form of the pattern used.) But the second piece of code takes substantially longer. Why? (I've done this several times; the spread is never less than about 6 seconds, and usually closer to 10, on approximately a 70 second runtime).

Timing[For[i = 1, i < 1000, i++,
      x = RandomReal[{0, 100}, 100000];
      Count[x, r_ /; r >= 50]
    ];
]

(* {68.6056, Null}} *)

Timing[For[i = 1, i < 1000, i++,
      x = RandomReal[{0, 100}, 100000];
      Count[x, _?(# >= 50 &)]
    ];
]

(* {79.1529, Null} *)
$\endgroup$
  • 1
    $\begingroup$ I'm not sure that there is a good reason why it has to be like this. It just happens to be like this in Mathematica 10.3. Both constructs involve evaluating some Mathematica code for each element of x, and theoretically both could be optimized in various ways ... The code that is being evaluated is clearly different, so it's not that surprising that there is a slight performance difference. $\endgroup$ – Szabolcs Nov 17 '15 at 16:05
  • 1
    $\begingroup$ However, if you want much better performance, use Total@UnitStep[x - 50]. This is of course not nearly as readable as Count, and it gets even messier if you change that >= to a >. To make it easier to use these constructs I wrote the BoolEval package, using which you can do Total@BoolEval[x >= 50]. Also consider using RepeatedTiming and really really avoid For ... if you need a procedural loop, use Do. $\endgroup$ – Szabolcs Nov 17 '15 at 16:07
  • $\begingroup$ @Szabolcs Thanks for the tips about UnitStep and RepeatedTiming. (And, I never use For, just for this example). $\endgroup$ – rogerl Nov 17 '15 at 21:13
  • $\begingroup$ @Xavier. You are exactly correct. I retract my comment: I clearly had all kinds of syntax errors. If you define f correctly, it doesn't result in a speed-up. $\endgroup$ – march Nov 18 '15 at 0:48
  • $\begingroup$ @Szabolcs However, I do take some issue with your term "slight performance difference". 11 seconds out of 68 is hardly slight... $\endgroup$ – rogerl Nov 18 '15 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.