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 NumPy sort
function with several different array sizes. The classic
quicksort and
merge sort algorithms have an average running time of
O(nlogn); so we will try to fit our result to such a model.
How to do it...
We will require arrays to sort.
Create arrays to sort.
We will create arrays of varying sizes containing random integer values:
times = numpy.array([]) for size in sizes: integers = numpy.random.random_integers(1, 10 ** 6, size)
Measure time.
In order to measure time, we need to create a timer and give it a function to execute and specify the relevant imports. After that, sort 100 times to get some data about the sorting times:
def measure(): timer = timeit.Timer('dosort()', 'from __main__ import dosort') return timer.timeit(10 ** 2)
Build measurement time arrays.
Build the measurement time arrays by appending times one by one:
times...