Skip to Content
Mastering Python
book

Mastering Python

by Rick Hattem
April 2016
Intermediate to advanced content levelIntermediate to advanced
486 pages
9h 21m
English
Packt Publishing
Content preview from Mastering Python

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(), ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Programming

Advanced Python Programming

Dr. Gabriele Lanaro, Quan Nguyen, Sakis Kasampalis
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips
Python for Geeks

Python for Geeks

Muhammad Asif

Publisher Resources

ISBN: 9781785289729Supplemental Content