list.count runs 40 times slower than manually counting
I recently noticed that list.count
runs extremely slow in both PyPy2 and PyPy3. See for example this simple benchmark:
n = q = 10000
A = [0] * n
def my_counter(A, a):
count = 0
for b in A:
count += a == b
return count
import time
l = time.clock()
for i in range(q):
my_counter(A, 1)
r = time.clock()
print("Time taken:", r - l)
l = time.clock()
for i in range(q):
A.count(1)
r = time.clock()
print("Time taken:", r - l)
Locally using PyPy3 (v3.7.10) I get
Time taken: 0.09564578769311112
Time taken: 3.9947766063414565
so my_counter
takes 0.1 s and list.count
takes 4 s. It is not reasonable that list.count takes 4 s to do 10^8 counts.