如何使用`dis.dis`来分析性能? [英] How does one use `dis.dis` to analyze performance?

查看:55
本文介绍了如何使用`dis.dis`来分析性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 的 dis 用于试验的库 &了解性能.下面是我尝试过的一个实验,结果如下.

I'm trying to use python's dis library to experiment with & understand performance. Below is an experiment i tried, with the results.

import dis

def myfunc1(dictionary):
    t = tuple(dictionary.items())
    return t

def myfunc2(dictionary, func=tuple):
    t = func(dictionary.items())
    return t

>>> dis.dis(myfunc1)

  4           0 LOAD_GLOBAL              0 (tuple)
              3 LOAD_FAST                0 (dictionary)
              6 LOAD_ATTR                1 (items)
              9 CALL_FUNCTION            0
             12 CALL_FUNCTION            1
             15 STORE_FAST               1 (t)

  5          18 LOAD_FAST                1 (t)
             21 RETURN_VALUE 

>>> dis.dis(myfunc2)

  4           0 LOAD_FAST                1 (func)
              3 LOAD_FAST                0 (dictionary)
              6 LOAD_ATTR                0 (items)
              9 CALL_FUNCTION            0
             12 CALL_FUNCTION            1
             15 STORE_FAST               2 (t)

  5          18 LOAD_FAST                2 (t)
             21 RETURN_VALUE    

现在,我明白了...

  • 4 &5 最左边是行号
  • 中间一列是机器调用的操作码
  • 右侧的列是对象(使用opargs?)
  • the 4 & 5 on the far left are the line numbers
  • the column in the middle is the opcodes that are called by the machine
  • the column on the right are the objects (with opargs?)

...但这在性能方面意味着什么?如果我试图决定使用哪个函数,我将如何使用 dis 来比较两者?

...But what does this all mean in terms of performance? If i were trying to make a decision on which function to use, how would i use dis to compare the two?

提前致谢.

推荐答案

您(或至少是普通人)无法通过查看不同的汇编代码来判断哪个更快.

You (or at least regular people) can't look at different assembly codes, and tell which one is faster.

尝试来自 IPython 的 %%timeit 魔法函数.

Try %%timeit magic function from IPython.

它会自动多次运行这段代码,并给你一个客观的答案.

It will automatically run the piece of code several times, and give you an objective answer.

我最近发现了这篇博文,它教你如何在 Python 中测量这些东西.不仅是时间,还有内存使用.这篇文章的亮点(至少对我来说)是它教你实现 %lprun 魔法功能.

I recently found this blog post that teaches how to measure these kind of things in Python. Not only time, but memory usage too. The higlight of the post (for me, at least) it's when it teaches you to implement the %lprun magic function.

使用它,您将能够逐行查看您的函数,并确切知道每个函数对花费的总时间的贡献.

Using it, you will be able to see your function line by line, and know exactly how much each one contribute to the total time spent.

我已经使用了几个星期了,非常棒.

I've been using for a few weeks now, and it's great.

这篇关于如何使用`dis.dis`来分析性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆