原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12233622.html

 

dis

可以使用dis模块来判断哪种代码的运行速度更快,具体的原理是:Python代码是由Python虚拟机执行的,Python虚拟机执行的是字节码,Python代码运行前会被编译为字节码,dis模块则可以对Python代码进行生成字节码操作。

e.g. 比较 a = list() 和 b = [] 两种创建空列表方法的运行速度

import dis

def func():
    a = list()
    b = []

dis.dis(func)

Console Output

Python dis

可以看出 a = list() 这种写法包括了 CALL_FUNCTION 行为, 在Python中进行 function call,需要创建一个栈,然后进行参数检查之类的操作,显然没有直接使用 [] 这种内置的C函数效率高

 

Reference

https://docs.python.org/3/library/dis.html

相关文章:

  • 2022-12-23
  • 2021-12-26
  • 2021-04-08
  • 2022-03-05
  • 2021-07-19
  • 2021-12-01
  • 2021-08-06
  • 2022-12-23
猜你喜欢
  • 2021-12-22
  • 2021-12-22
  • 2022-12-23
  • 2022-12-23
  • 2021-08-09
相关资源
相似解决方案