Python中not not x 与bool(x)代码的写法有何不同
Admin 2022-06-16 群英技术资讯 478 次浏览
他们都可以把 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万次。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
最近进行python基础培训,课下作业制作万年历,之前没做过,感觉里面还是有很多需要学的,下面这篇文章主要给大家介绍了关于python新手练习实例之万年历的相关资料,需要的朋友可以参考下
这篇文章主要介绍了Python网络编程之ZeroMQ知识总结,文中有非常详细的代码示例,对正在学习python的小伙伴们有非常好的帮助,需要的朋友可以参考下
python怎样写一个自幂数?首先,自幂数是指一个 n 位数,它的每个位上的数字的 n 次幂之和等于它本身。下面给大家分享的是python实现自幂数的代码,感兴趣的朋友可以参考。
Python内置函数-frozenset() 函数。frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
在python中,默认是按照ascii的大小比较的;字符串按位比较,两个字符串第一位字符的ascii码谁大,字符串就大,不再比较后面的;
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008