【问题标题】:"Non-equal" or "greater than" is quicker?“不等于”或“大于”更快?
【发布时间】:2013-01-23 14:08:32
【问题描述】:

我想知道以下哪项对于元组(也对于列表或 int)执行得更快:

a_tuple = ('a', 'b',)
  1. if (len(a_tuple) != 0): pass

  2. if (len(a_tuple) > 0): pass

我做了一些 timeit 实验,结果非常相似(每次运行 timeit 100000 次迭代时都会有所不同)。我只是想知道是否有时间收益。

【问题讨论】:

  • 像这样的微优化很少有好处。如果您需要速度,请将其外包给 C。

标签: python python-3.x python-2.7


【解决方案1】:

使用not a_tupleTrue,如果为空)或tupleTrue,如果不为空)而不是测试长度:

if a_tuple:
    pass

或者,作为一个示范胜于雄辩:

>>> if not ():
...     print('empty!')
...
empty!
>>> if (1, 0):
...     print('not empty!')
...
not empty!

除了这是一个微优化之外,测试空元组的虚假性也更快。如果对速度有疑问,请使用timeit 模块:

>>> import timeit
>>> a_tuple = (1,0)
>>> def ft_bool():
...     if a_tuple:
...         pass
... 
>>> def ft_len_gt():
...     if len(a_tuple) > 0:
...         pass
... 
>>> def ft_len_ne():
...     if len(a_tuple) != 0:
...         pass
... 
>>> timeit.timeit('ft()', 'from __main__ import ft_bool as ft')
0.17232918739318848
>>> timeit.timeit('ft()', 'from __main__ import ft_len_gt as ft')
0.2506139278411865
>>> timeit.timeit('ft()', 'from __main__ import ft_len_ne as ft')
0.23904109001159668

【讨论】:

  • 另外,速度快了两倍。
  • 等等,如果你有一个空元组的实例,“if a_tuple”怎么可能是假的?
  • @Ivaylo:因为空元组是“假的”。在布尔上下文中,它测试为 False,就像空字符串或 0(任何数字类型)一样。见docs.python.org/2/reference/expressions.html#boolean-operations
  • @Martijn:非常感谢您的帮助。确实,我记得类似的东西,但很高兴再次阅读它。这对我来说可以节省大量时间,因为我有数百万次这样的比较。
猜你喜欢
  • 2013-12-17
  • 2011-01-25
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2013-11-11
  • 2020-11-20
相关资源
最近更新 更多