4 ms·
I always had the impression that the more "RPython-like" your Python code is, the better PyPy can optimize it. If that is true, then I see a lot of value in thi
by dr_zoidberg 11y ago
I always had the impression that the more "RPython-like" your Python code is, the better PyPy can optimize it. If that is true, then I see a lot of value in this post. However I'm unsure how much truth is in my belief.
- TheLoneWolfling 11y agoI'd agree. The thing is: for stock Python, you want to minimize interpreter load. Use a lot of list comprehensions, that sort of thing. Whereas with PyPy you want to do the opposite. For instance, I have the following two functions: def atLeast2(a,b,num): return sum(x==y for x,y in itertools.zip_longest(reversed(bin(a).partition('b')[-1]), reversed(bin(b).partition('b')[-1]), fillvalue='0')) >= num def atLeast4(a,b,num): count = 0 while a > 0 or b > 0: x = a % 2 y = b % 2 if x == y: count += 1 if count >= num: return True a //= 2 b //= 2 return count >= num In Python, atLeast2 is ~2.7x faster than atLeast4. In Pypy, atLeast2 is 1.9x slower than atLeast4. (The ordering is roughly, using relative numbers (lower = faster), and checking for at least 96 bits in common out of 128 for random inputs: 1.0 pypyatLeast 3.2515636711379905 pypyatLeast4 3.5864477527073473 pypyatLeast3 4.430998164947921 pythonatLeast 5.903265617327027 pythonatLeast2 6.306511850301104 pypyatLeast2 15.832777648548758 pythonatLeast4 15.870273448605621 pythonatLeast3 Note that atLeast2 is slower in PyPy than Python! def atLeast(a, b, num): count = 0 for x, y in zip(bin(a).partition('b')[-1], bin(b).partition('b')[-1]): if x == y: count += 1 if count >= num: return True return False def atLeast3(a,b,num): count = 0 while a > 0 or b > 0: x = a % 2 y = b % 2 if x == y: count += 1 a //= 2 b //= 2 return count >= num )
- tachion 11y agoYou should report this scenario to PyPy - they're waiting for and love examples where Python is faster than PyPy.
- TheLoneWolfling 11y agoI shall do so. Thank you for reminding me! Edit: it appears to be covered by https://bitbucket.org/pypy/pypy/issues/2100/sum-map-foo-is-much-slower-than-for-loop https://bitbucket.org/pypy/pypy/issues/2100/sum-map-foo-is-m...