【发布时间】:2018-09-09 14:22:06
【问题描述】:
我发现了一个有趣的性能优化。而不是使用all():
def matches(self, item):
return all(c.applies(item) for c in self.conditions)
我已经分析过,使用循环代替它会更快:
def matches(self, item):
for condition in self.conditions:
if not condition.applies(item):
return False
return True
使用all(),分析器显示另外1160 个<genexpr> 调用:
4608 function calls (4600 primitive calls) in 0.015 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
580 0.002 0.000 0.008 0.000 rule.py:23(matches)
1160 0.002 0.000 0.005 0.000 rule.py:28(<genexpr>)
使用for 循环,没有<genexpr> 调用:
2867 function calls (2859 primitive calls) in 0.012 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
580 0.002 0.000 0.006 0.000 rule.py:23(matches)
我的问题是差异来自哪里?我的第一个想法是 all 评估所有条件,但事实并非如此:
def foo():
print('foo')
return False
all(foo() for _ in range(1000))
foo
【问题讨论】:
-
我相信这是最近有人问和回答的。正在尝试查找重复项...
-
你确定它是重复的吗?我不太确定。
-
Why simple for loop with simple if condition is faster than conditional generator expression 很接近,但不是我要找的;重新打开,试图找到更近的。
-
...
forloop vsall()execution speed 是我想要的。但是,不能两次关闭同一个问题,所以我需要把它留给标签中的另一个金徽章来决定它是否准确。
标签: python python-3.x