by masklinn · 11y ago · 0 comments
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
)Edit: it appears to be covered by https://bitbucket.org/pypy/pypy/issues/2100/sum-map-foo-is-m...