Python: Timing, Benchmark

By Xah Lee. Date: . Last updated: .

Timing, Compare Speed

to time a function or compare the speed of different ways to code the same thing, use the builtin lib timeit.

import timeit

there are several ways to call it:

Example: Time a Code by String

import timeit

tt = timeit.timeit("""map(lambda x: x+1, range(1000))""", number=1000)
print(tt)
# 0.00023860000510467216

Example: Time a Function with No Argument

import timeit

xinput = range(1000)

def f1():
    """add 1 to global xinput"""
    return map(lambda x: x + 1, xinput)

tt = timeit.timeit(f1, number=1000)
print(tt)
# 0.0002162000018870458

Example: Time a Function with Argument

import timeit

# timing a function with args


def f2(xlist):
    """add 1 to all element"""
    return map(lambda x: x + 1, xlist)

xinput = range(1000)

# testing a function with arg
tt = timeit.timeit(lambda: f2(xinput), number=1000)
print(tt)
# 0.00023639999562874436