gpt4 book ai didi

Python:为什么 `not not x` 比 `bool(x)` 快两倍多

转载 作者:行者123 更新时间:2023-12-01 00:09:05 25 4
gpt4 key购买 nike

考虑一下:

>>> from timeit import timeit
>>> timeit('x = 1; t = bool(x)')
0.08783805199999506
>>> timeit('x = 1; t = not not x')
0.018457599000015534

现在我知道函数调用通常会给您带来开销,但通常情况下,小的常见情况(例如这个)是由编译器和解释器优化的。

那么这里到底发生了什么?

最佳答案

typically, the small common cases (such as this one) are optimized by compilers and interpreters

也许在具有 JIT 的解释器中,但 Python 的引用实现没有。它实际上是在当前全局命名空间字典中对 bool 名称执行哈希查找,但没有找到它,然后退回到内置命名空间字典中的哈希查找,找到 bool > 输入,并执行 __new____init__

相比之下,not not x 可以跳过所有这些。它仍然需要执行x的convert-to-boolean钩子(Hook),但是bool(x)也必须这样做。 not not x 必须做而 bool(x) 不做的事情是两个否定和一个将 bool 转换为 bool 的操作,但这更直接C 级别(并且有一个 bool 到 bool noop 转换的快速路径)。

关于Python:为什么 `not not x` 比 `bool(x)` 快两倍多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com