pythontimetimeit

How to use timeit module


How do I use timeit to compare the performance of my own functions such as "insertion_sort" and "tim_sort"?


Solution

  • The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).

    Here is an example of how to set up a test for sorting:

    >>> import timeit
    
    >>> setup = '''
    import random
    
    random.seed('slartibartfast')
    s = [random.random() for i in range(1000)]
    timsort = list.sort
    '''
    
    >>> print(min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000)))
    0.04485079200821929
    

    Note that the series of statements makes a fresh copy of the unsorted data on every pass.

    Also, note the timing technique of running the measurement suite seven times and keeping only the best time — this can really help reduce measurement distortions due to other processes running on your system.