Skip to content

Code profiling

The timeit module

The timeit module measures the execution time of code snippets in Python. This is a precise method that doesn't take background processes into account. In addition, it runs the code multiple times (million times by default), making the result statistically significant.

To use the module, perform it as follows:

    timeit.timeit(stmt, setup, number),
where:

  • stmt denotes the block of code whose execution time we want to measure,
  • setup is the code that will be executed before executing statement, e.g. importing the necessary modules,
  • number is the number of times the code is to be executed,

Example 1

Suppose we want to measure the execution time of any function. For this purpose, we create the code variable, in which we put the code of this function, and the setup variable, in which we will import the appropriate module.

    import timeit

    setup = "from math import sqrt"

    code = '''
    def func():
        return [sqrt(x) for x in range(100)]
    '''

    print(timeit.timeit(stmt=code, setup=setup))

The result of running the above code will be the execution time (in seconds) of one million repetitions of the code passed as stmt. To know the time for one iteration - just divide the result by number.

    0.08462022099411115

Example 2

This time we would like to compare the execution time of two searches for an item in a list: linear and binary. For this purpose, we import into the setup variable the functions implementing these algorithms and the random module, and then use the timeit module to measure the execution time of both functions.

    if __name__ == "__main__":
        setup = '''
    from __main__ import linear_search, binary_search
    import random
    '''

        linear_search_code = '''
    lst = sorted([random.randint(0, 1000000) for _ in range(1000)])
    to_find = random.randint(0, 1000000)
    result = linear_search(lst, to_find)
    '''

        binary_search_code = '''
    lst = sorted([random.randint(0, 1000000) for _ in range(1000)])
    to_find = random.randint(0, 1000000)
    result = binary_search(lst, to_find)
    '''

        print(timeit.timeit(stmt=linear_search_code,
                            setup=setup,
                            number=1000))
        print(timeit.timeit(stmt=binary_search_code,
                            setup=setup,
                            number=1000))

The result of running the above code will be:

    1.5267830700613558
    1.4292314919875935

So we can see that binary search is actually faster than linear, so it's worth learning and applying algorithms. ;)