python中not not x 与bool(x)有哪些区别(python,开发技术)

时间:2024-05-08 11:44:02 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

他们都可以把 x 变成一个布尔类型的值:

>>>x=123>>>notnotxTrue>>>bool(x)True>>>

那么谁更快呢?我们写段代码,跑个 100 万次,来比较下谁更快:

importtimeitdefbool_convert(x):returnbool(x)defnotnot_convert(x):returnnotnotxdefmain():trials=10_000_000kwargs={"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()

运行结果如下:

python中not not x 与bool(x)有哪些区别

其实 bool(x) 慢的原因在于它是一个函数调用,而 not not x 就是一条指令,具有更快捷的转换为布尔值的路径,这一点可以从字节码可以看出来:

python中not not x 与bool(x)有哪些区别

bool(x) 多了 LOAD_GLOBAL CALL_FUNCTION

这里附一下相关字节码的官方说明:

LOAD_GLOBAL(namei)Loadstheglobalnamedco_names[namei]ontothestack.CALL_FUNCTION(argc)Callsacallableobjectwithpositionalarguments.argcindicatesthenumberofpositionalarguments.Thetopofthestackcontainspositionalarguments,withtheright-mostargumentontop.Belowtheargumentsisacallableobjecttocall.CALL_FUNCTIONpopsallargumentsandthecallableobjectoffthestack,callsthecallableobjectwiththosearguments,andpushesthereturnvaluereturnedbythecallableobject.UNARY_NOTImplementsTOS=notTOS.

最后:

从结果来看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一个函数调用,函数调用需要参数压入栈顶,堆栈的顶部包含位置参数,最右边的参数在顶部,参数下面是要调用的可调用对象。CALL_FUNCTION 从堆栈中弹出所有参数和可调用对象,使用这些参数调用可调用对象,并推送可调用对象返回的返回值,这一过程比一个 not 指令要慢得多。

不过我仍然推荐你使用 bool(x) ,因为它的可读性更高,而且,我们也不太可能调用它 100万次。

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:python中not not x 与bool(x)有哪些区别的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Python如何制作子弹图下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18