Profiling Python code using IPython's %timeit function

Often, when we are working in the Python REPL, we would like to be able to quickly and easily benchmark a line of code or a function. IPython makes this possible through a magic function called timeit.

How to do it…

Perform the following set of steps to try out %timeit to profile the code:

  1. Open up a new terminal and change to the direction of the asa.py source code.
  2. Fire up IPython by typing the following:
    ipython
    
  3. Let's see how fast or slow the built-in square root function is, as follows:
    In [1]: import math
    In [2]: %timeit math.sqrt(10000)
    
  4. This should produce output similar to the following:
    10000000 loops, best of 3: 166 ns per loop
    
  5. We see that %timeit, due to the rapid execution of the math.sqrt() method, tested the function execution 10,000,000 times to get a more accurate measurement.
  6. Next, we will use %timeit to test the main loop of the asa code calculation. For this, we must first import the relevant functions:
    In [2]: from asa import *
    In [3]: import math
    In [4]: from vector3d import pos_distance, Vector3d, pos_distance_sq
    In [5]:  import molecule
    
  7. We then create the variables that are required to call the calculate_asa function:
    In [13]: mol = molecule.Molecule('1R0R.pdb')
    In [14]: atoms = mol.atoms()
    In [15]: molecule.add_radii(atoms)
    In [16]: n_sphere = 960 
    
  8. We then use the magic %timeit command to profile the function in question:
    In [18]: %timeit asas = calculate_asa(atoms, 1.4, n_sphere)
    
  9. This produces the output that agrees relatively well with the simple Unix time command:
    1 loops, best of 3: 52.5 s per loop
    

Notice that there appears to be a bit of an overhead added to the execution time using %timeit.

How it works…

The %timeit magic function is a bit smarter than the previously mentioned profiling tools in that it will run the specified code multiple times to get a better estimate of the code's true execution time. If the code takes longer to run, it will reduce the number of repetitions performed for benchmarking.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.177.14