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

Steven D'Aprano steve at pearwood.info
Tue Nov 23 15:12:03 CET 2010


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.


 > 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, 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.



  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



-- 
Steven



More information about the Tutor mailing list