Python 中类似代码的速度差异
Speed difference in similar code in Python
我有这3个功能:
def is_compatible(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if isinstance(values[0], allowed_types):
return all(isinstance(item, allowed_types) for item in values)
return False
def is_compatible2(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if all(isinstance(item, allowed_types) for item in values):
return True
return False
def is_compatible3(values):
supported_types = [(str, unicode), (int, long)]
return any(
all(isinstance(item, allowed_types) for item in values) for
allowed_types in supported_types
)
有人可以向我解释一下,为什么当我 运行 他们在 timetit 中使用 [1,2,3,4,5] 作为参数时,结果是 2.47、3.07 和 3.94?所以第一个最快,最后一个最慢。我根本看不出这些速度差异的任何原因。谢谢
您的答案似乎在这里:Why is Python's 'all' function so slow?
在 all
中设置迭代器需要时间。
在您的第一个函数中,您只执行一次。在你的第二个功能中,你偶尔会这样做两次。所以第一胜过第二。
出于同样的原因,您的第二名再次击败第三名。有更多的开销需要设置。围绕 for allowed_types in ...
调用 any
比简单地 for allowed_types in ...
.
开销更大
我有这3个功能:
def is_compatible(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if isinstance(values[0], allowed_types):
return all(isinstance(item, allowed_types) for item in values)
return False
def is_compatible2(values):
supported_types = [(str, unicode), (int, long)]
for allowed_types in supported_types:
if all(isinstance(item, allowed_types) for item in values):
return True
return False
def is_compatible3(values):
supported_types = [(str, unicode), (int, long)]
return any(
all(isinstance(item, allowed_types) for item in values) for
allowed_types in supported_types
)
有人可以向我解释一下,为什么当我 运行 他们在 timetit 中使用 [1,2,3,4,5] 作为参数时,结果是 2.47、3.07 和 3.94?所以第一个最快,最后一个最慢。我根本看不出这些速度差异的任何原因。谢谢
您的答案似乎在这里:Why is Python's 'all' function so slow?
在 all
中设置迭代器需要时间。
在您的第一个函数中,您只执行一次。在你的第二个功能中,你偶尔会这样做两次。所以第一胜过第二。
出于同样的原因,您的第二名再次击败第三名。有更多的开销需要设置。围绕 for allowed_types in ...
调用 any
比简单地 for allowed_types in ...
.