O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Profiling with timeit

timeit is a module that allows you to time pieces of code. It is part of the standard Python library. We will time the sort() NumPy function with several array sizes. The classic quicksort and merge sort algorithms have an average running time of O(N log N), so we will try to fit our result to such a model.

How to do it...

We will require arrays to sort:

  1. Create arrays to sort varying sizes containing random integer values:
    times = np.array([])
    
    for size in sizes:
        integers = np.random.random_integers (1, 10 ** 6, size)
  2. To measure time, create a timer, give it a function to execute, and specify the relevant imports. Then, sort 100 times to get data about the sorting times:
    def measure(): timer = timeit.Timer('dosort()', 'from __main__ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required