python中notnotx与bool(x)的区别 他们都可以把 x 变成一个布尔类型的值: x = 123 not not x True bool(x) True 那么谁更快呢?我们写段代码,跑个 100 万次,来比较下谁更快: import timeit def bool_convert(x): return bool(x) def notnot_convert(x): return not not x def main(): trials ...
他们都可以把 x 变成一个布尔类型的值:
>>> x = 123
>>> not not x
True
>>> bool(x)
True
>>>
那么谁更快呢?我们写段代码,跑个 100 万次,来比较下谁更快:
import timeit
def bool_convert(x):
return bool(x)
def notnot_convert(x):
return not not x
def main():
trials = 10_000_000
kwargs = {
"setup": "x=42",
"globals": globals(),
"number": trials,
}
notnot_time = timeit.timeit("notnot_convert(x)", **kwargs)
bool_time = timeit.timeit("bool_convert(x)", **kwargs)
print(f"{bool_time = :.04f}")
print(f"{notnot_time = :.04f}")
if __name__ == "__main__":
main()
运行结果如下:
其实 bool(x)
慢的原因在于它是一个函数调用,而 not not x
就是一条指令,具有更快捷的转换为布尔值的路径,这一点可以从字节码可以看出来:
bool(x)
多了 LOAD_GLOBAL
和 CALL_FUNCTION
。
这里附一下相关字节码的官方说明:
LOAD_GLOBAL(namei)
Loads the global named co_names[namei] onto the stack.
CALL_FUNCTION(argc)
Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.
UNARY_NOT
Implements TOS = not TOS.
最后:
从结果来看,not not x 比 bool(x)
更快,主要原因在于 bool(x)
是一个函数调用,函数调用需要参数压入栈顶,堆栈的顶部包含位置参数,最右边的参数在顶部,参数下面是要调用的可调用对象。CALL_FUNCTION
从堆栈中弹出所有参数和可调用对象,使用这些参数调用可调用对象,并推送可调用对象返回的返回值,这一过程比一个 not
指令要慢得多。
不过我仍然推荐你使用 bool(x)
,因为它的可读性更高,而且,我们也不太可能调用它 100万次。
到此这篇关于python
中not not x
与 bool(x)
的区别的文章就介绍到这了,更多相关not not x与bool(x) 的区别内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
本文标题为:python中not not x 与bool(x) 的区别


基础教程推荐
- 创建python虚拟环境(在ubuntu16.04中) 2023-09-04
- linux 安装 python3 2023-09-03
- 使用Pycharm创建一个Django项目的超详细图文教程 2022-09-02
- 远程和Ubuntu服务器进行Socket通信,使用python和C#(准备篇) 2023-09-05
- Python+OpenCV实战之实现文档扫描 2022-10-20
- Python爬虫爬取属于自己的地铁线路图 2023-08-05
- 云服务器Ubuntu更改默认python版本 2023-09-03
- windows下面使用多版本Python安装指定版本的虚拟环境 2023-09-04
- python验证多组数据之间有无显著差异 2023-08-08
- MySQL数据优化-多层索引 2023-08-11