Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one use `dis.dis` to analyze performance?

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    

Now, i understand that...

  • 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?)

...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?

Thanks in advance.

like image 773
Noob Saibot Avatar asked Oct 11 '13 16:10

Noob Saibot


1 Answers

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

Try %%timeit magic function from IPython.

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

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.

like image 175
Lucas Ribeiro Avatar answered Nov 02 '22 18:11

Lucas Ribeiro