Timing

Notebooks are an ideal way to play around with performance tuning.

In this example we'll compare three different ways of counting the number of words in a string.


In [1]:
# Setup sample data
import random, string

def randomword():
    return ''.join([random.choice(string.ascii_lowercase) for 
                    _ in range(random.randrange(1, 8))])

sample = ' '.join([randomword() for _ in range(10000)]);

In [2]:
# Method one
def count(txt):
    return len(txt.split())

%timeit count(sample)


1000 loops, best of 3: 743 µs per loop

In [3]:
# Method two
import re
def count2(txt):
    return len(re.findall(r' ', txt))

%timeit count2(sample)


1000 loops, best of 3: 894 µs per loop

In [4]:
# Method three
def count3(txt):
    count = 1
    for i in txt:
        if i == ' ':
            count += 1

%timeit count3(sample)


100 loops, best of 3: 3.88 ms per loop

Conclusion

The %timeit magic invocation is a convenient way to quickly test function performance.