O'Reilly logo

Mastering Python by Rick van Hattem

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Line profiler

line_profiler is actually not a package that's bundled with Python, but it's far too useful to ignore. While the regular profile module profiles all (sub)functions within a certain block, line_profiler allows for profiling line per line within a function. The Fibonacci function is not best suited here, but we can use a prime number generator instead. But first, install line_profiler:

 pip install line_profiler

Now that we have installed the line_profiler module (and with that the kernprof command), let's test line_profiler:

import itertools @profile def primes(): n = 2 primes = set() while True: for p in primes: if n % p == 0: break else: primes.add(n) yield n n += 1 if __name__ == '__main__': total = 0 n = 2000 for prime in itertools.islice(primes(), ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required