I had to develop on a very old laptop - Pentium I, 64MB of RAM and Windows 98. Python was my language of choice, the version was 2.4.something, probably not the latest. (I have no possibility to check the exact version now, i’ll update it as soon as i can).
Since i was working on such a slow device, i had to optimize as much as i could. I tried profile and pstats modules but i got to several small functions which i had to improve. Because I’m new in python, i did some benchmarks on several things, which might be obvious for some, but were not obvious for a python newbie (me). I’d really like to know whether the results are as expected.
Here they are, each code section has comment of a time it took:
import time
# x**2 vs x*x:
# 9.5 sec:
start = time.time()
for j in range(500000):
t = [j, j]
z = (t[0] - 1)*(t[1] - 1)
if j == 0: print z
print time.time() - start
# 20.2 sec:
start = time.time()
for j in range(500000):
t = [j, j]
z = (t[0] - 1)**2
if j == 0: print z
print time.time() - start
elmLst = []
for i in range(100):
elmLst.append([0,1,2,3,4,5,6,7,8,9,0])
# reduce() vs loop:
# 9 sec:
start = time.time()
for j in range(1000):
z = reduce(lambda p1,p2: (i1 + i2 for i1, i2 in zip(p1, p2)), elmLst)
if j == 0: print z
print time.time() - start
# 11 sec:
start = time.time()
for j in range(1000):
z = None
for e in elmLst:
if z == None: z = e
else:
z = [e1+e1 for e1, e2 in zip(z, e)]
if j == 0: print z
print time.time() - start
e1 = range(100)
e2 = range(100)
# […] vs map()
# 7 secs:
start = time.time()
for j in range(10000):
z = [e[0]*e[1] for e in zip(e1, e2)]
if j == 0: print z
print time.time() - start
# 15 secs:
nowstart = time.time()
for j in range(10000):
z = map(lambda e: e[0]*e[1], zip(e1, e2))
if j == 0: print z
print time.time() - start
Technorati Tags: python, benchmark, programming