Python: Timing Functions with timeit

By Xah Lee. Date:

This page shows you how to use timeit module for timing the speed of a function that has one or more parameter.

Suppose you have 2 functions f1, f2, with different implementations. You want to see the speed of f1, f2, when the argument is huge.

mydata = generate_data(xyz)

Each function takes one arg, the mydata. mydata needs to be generated, and itself takes long time to run. You want all functions must be tested using the same same data, and the data generation shouldn't run more than once.

Here's how you do it.

# -*- coding: utf-8 -*-
# python
# example of using timeit.timeit
# testing the speed of a function that takes one argument

mydata = 5

def f1(x):
    return x+1

import timeit

print timeit.timeit("f1(mydata)", setup = "from __main__ import f1, mydata", number=1)

If you have a question, put $5 at patreon and message me.