在比较 Python 中的各种等效形式时filter(xs, lambda x: x != el)
,我偶然发现了一些令我惊讶的东西。考虑以下形式:
def method1(xs, el):
p = lambda x: x != el
return [x for x in xs if p(x)]
def method2(xs, el):
return [x for x in xs if (lambda y: y != el)(x)]
我希望 Python 只构建一次 lambda,然后将其存储在一个临时变量中,这样两种形式的性能都差不多。method1
由于名称查找,甚至可能表现更差。
但是当我对它们进行基准测试时,结果发现它们的method2
表现始终比method1
. 为什么是这样?是否为每次迭代重建 lambda?
我的基准脚本(在一个单独的模块中,并期望methods
包含method1
and method2
)如下:
import math, timeit
def bench(n,rho,z):
pre = """\
import random
from methods import %(method)s
x = [(random.randint(0,%(domain)i)) for r in xrange(%(size)i)]
el = x[0]\
"""
def testMethod(m):
mod = pre % { 'method': m, 'domain': int(math.ceil(n / rho)), 'size': n }
return timeit.timeit("%s(x, el)" % m, mod, number = z)/(z * n)
print "Testing", n, rho, z
return tuple(testMethod(m) for m in ("method1", "method2"))
n = 31
min_size, max_size = 10.0**1, 10.0**4
size_base = math.pow(max_size / min_size, 1.0/(n-1))
# size_default = 10**3
#min_sel, max_sel = 0.001, 1.0
#sel_base = math.pow(max_sel / min_sel, 1.0/(n-1))
sel_default = 0.001
tests = [bench(int(min_size*size_base**x), sel_default, 100) for x in xrange(n)]
#tests = [bench(size_default, min_sel*sel_base**x, 100) for x in xrange(n)]
def median(x):
x = list(sorted(x))
mi = int(len(x)/2)
if n % 2 == 0:
return x[mi]
else:
return (x[mi] + x[mi+1])/2
def madAndMedian(x):
meh = median(x)
return meh, median([abs(xx - meh) for xx in x])
for z in zip(*tests):
print madAndMedian(z)