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 [45]:
# 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 [46]:
# Method one
def count(txt):
    return len(txt.split())

%timeit count(sample)


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

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

%timeit count2(sample)


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

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

%timeit count3(sample)


100 loops, best of 3: 3.34 ms per loop

Conclusion

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