[Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose

Richard D. Moores rdmoores at gmail.com
Tue Nov 23 18:50:59 CET 2010


On Tue, Nov 23, 2010 at 06:12, Steven D'Aprano <steve at pearwood.info> wrote:
> Richard D. Moores wrote:
>>
>> I've always disliked using "if not n % 2"  to test for even/odd ints
>> because of its convoluted logic.
>
> I don't find it convoluted. It's not quite as straightforward as a
> hypothetical "if even(n)", but it's pretty straightforward. Perhaps you just
> need to get used it it.

OK, somewhat convoluted. And after messing around with it for these
tests, I'm used to it now.

>> But I ran some speed tests and found
>>
>> it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to
>> 9.5% faster, depending on the integer tested - size and whether odd or
>> even.
>
> I suspect that the time difference you're seeing has nothing to do with it
> being even or odd,

I only threw in odd vs even out of curiosity. But I rand x1 against x2
against your x3 for the same ints as before:
<http://tutoree7.pastebin.com/KYbpza0V>. I show the original x1 vs. x2
results, followed by 3 sets that include x3. I think you can see that
odd ints take longer in almost all cases than evens.

>but merely random fluctuations.But regardless, this truly
> is a micro-optimization. Given the results you show, you potentially save
> all of (approx) 0.0000004 second per test.

Sure, but I've satisfied my curiosity.

>  See the speed testing script and results at
>>
>> <http://tutoree7.pastebin.com/iragLgDz>.
>
>
> You missed what I predict will be even faster:
>
> def x3(n):
>    return not n % 2

Yes, generally faster, but marginally. Thanks for the idea.

Dick


More information about the Tutor mailing list