7.6 List vs. array Performance: Introducing %timeit

  • Most array operations execute significantly faster than corresponding list operations
  • IPython %timeit magic command times the average duration of operations

Timing the Creation of a List Containing Results of 6,000,000 Die Rolls

In [1]:
import random
In [2]:
%timeit rolls_list = \
   [random.randrange(1, 7) for i in range(0, 6_000_000)]
6.88 s ± 276 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  • By default, %timeit executes a statement in a loop, and it runs the loop seven times
  • If you do not indicate the number of loops, %timeit chooses an appropriate value
  • After executing the statement, %timeit displays the statement’s average execution time, as well as the standard deviation of all the executions

Timing the Creation of an array Containing Results of 6,000,000 Die Rolls

In [3]:
import numpy as np
In [4]:
%timeit rolls_array = np.random.randint(1, 7, 6_000_000)
75.2 ms ± 2.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60,000,000 and 600,000,000 Die Rolls

In [5]:
%timeit rolls_array = np.random.randint(1, 7, 60_000_000)
916 ms ± 26.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [6]:
%timeit rolls_array = np.random.randint(1, 7, 600_000_000)
10.3 s ± 180 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Customizing the %timeit Iterations

In [7]:
%timeit -n3 -r2 rolls_array = np.random.randint(1, 7, 6_000_000)
74.5 ms ± 7.58 ms per loop (mean ± std. dev. of 2 runs, 3 loops each)

Other IPython Magics

IPython provides dozens of magics for a variety of tasks—for a complete list, see the IPython magics documentation. Here are a few helpful ones:

  • %load to read code into IPython from a local file or URL.
  • %save to save snippets to a file.
  • %run to execute a .py file from IPython.
  • %precision to change the default floating-point precision for IPython outputs.
  • %cd to change directories without having to exit IPython first.
  • %edit to launch an external editor—handy if you need to modify more complex snippets.
  • %history to view a list of all snippets and commands you’ve executed in the current IPython session.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.