Python中类似代码的速度差

2024-06-07 22:58:39 发布

您现在位置: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]作为arg运行它们,结果是2.47、3.07和3.94?所以第一个是最快的,最后一个是最慢的。我根本看不出这些速度差异的原因。谢谢。你知道吗


Tags: inforreturnisdefunicodeitemlong
1条回答
网友
1楼 · 发布于 2024-06-07 22:58:39

你的答案似乎在这里:Why is Python's 'all' function so slow?

all中设置迭代器需要时间。你知道吗

在你的第一个函数中,你只做一次。在你的第二个函数中,你偶尔会做两次。所以第一个胜过第二个。你知道吗

你的第二个又因为同样的原因打败了第三个。有更多的开销要设置。围绕for allowed_types in ...any的调用比简单的for allowed_types in ...开销更大。你知道吗

相关问题 更多 >

    热门问题