Pythonic laziness: good practice and fast code#
“Premature optimization is the root of all evil.” — Donald E. Knuth, 1974
In Python the same result can be computed in many ways, and the running times of different programs can differ by several orders of magnitude. This chapter shows that the fastest program is usually the one written “lazily,” in both senses of the word. Programmer’s laziness is the principle of not computing what can be derived and not writing what has already been written. Instead of a loop we use a formula; instead of our own function, a ready-made one from the standard library, NumPy, SciPy, or SymPy. Lazy evaluation means computing values only when they are needed: generators and iterators stop working as soon as they know the answer, and they do not keep everything in memory.
All the examples come from the code of the course’s lectures and labs: Horner’s scheme and bisection, Newton’s method, interpolation and quadrature from Lecture 5; Gaussian elimination from Lecture 6; MiniCAS from Lecture 3; the kNN model from Lecture 8; the Game of Life from Lab 8. The starting point is the instructor’s study of Python performance (a comparison of a loop and a generator), and some of the examples draw on the book by T. Altenkirch and I. Triguero Conceptual Programming with Python (2020). Every timing in this chapter is measured when the page is built, and a hidden code cell checks the sentences about timings at every build.
Part 1. How to measure the running time of a program — how to measure time honestly: the contract,
%timeit, the median of many measurements, a loop in a cell vs. in a function, measurement pitfalls, the profiler.Part 2. Mathematics first, then the algorithm — mathematics and the algorithm first: a formula instead of a loop, a cache for recursion (
@cache), parametrization instead of search, the search order in sudoku.Part 3. Lazy evaluation: generators and iterators — generators and iterators: short-circuiting
any/all, memory, infinite sequences, the lazy sieve of Eratosthenes and its limits.Part 4. The standard library: built-in functions and data structures — the standard library:
sumandmath.fsum, a set instead of a list,Counter,heapq,itertools,math.isqrt,powwith a modulus, building lists and strings.Part 5. NumPy: the loop moved to C — NumPy: the loop moved to C, vectorization over independent tasks, pitfalls (
np.vectorize, integer overflow, memory in broadcasting).Part 6. Ready-made algorithms: SciPy and linear algebra — ready-made algorithms: LAPACK and BLAS,
brentq, barycentric interpolation,quad, exact computation and verification, which is cheaper.Part 7. SymPy: symbolic once, numeric many times — SymPy: symbolic computation done once,
lambdify,Poly, a specific operation instead ofsimplify, rational numbers and binary splitting.Part 8. Cheat sheet: good practice and pitfalls — a cheat sheet: the ladder of laziness (the order of decisions), correctness pitfalls in mathematical code, readable code, a summary of part 9, references.
Part 9. Compilation and parallel computing — compilation and parallel computing: Numba, a compiler that finds the formula by itself, loops that cannot be vectorized, threads, processes, and
prange, Amdahl’s law.
Map of examples#
Example |
What it shows |
Where |
Connection to the course |
|---|---|---|---|
two programs summing \(i+j\) |
the same loop runs faster in a function than in a notebook cell |
the instructor’s study |
|
\(S(n)=n^2(n-1)\) |
the formula is orders of magnitude faster than any loop |
part 1 |
Lecture 1, §1.2 |
profile of the trapezoidal rule |
the time goes into the |
parts 1 and 7 |
Lecture 5, §5.4 |
power sums \(1^p+\dots+n^p\) |
a formula instead of a loop |
Lecture 5, §5.3 |
|
\(\binom{49}{6}\) recursively |
tens of millions of calls; |
part 2 |
Altenkirch, Triguero; Lecture 1 |
Collatz steps for \(n\le10^5\) |
memoizing results inside a loop |
part 2 |
Lecture 1, Lab 8 |
Pythagorean triples |
Euclid’s parametrization instead of three loops |
part 2 |
Lecture 1, §1.2 |
sudoku |
the search order, a solution checker |
part 2 |
Altenkirch, Triguero; Lectures 7 and 8 |
the Collatz sequence with |
a generator stops once it knows the answer |
Altenkirch, Triguero |
|
\(n^2+n+41\) |
a counterexample to Euler’s polynomial, found lazily |
part 3 |
|
the lazy sieve of Eratosthenes |
|
part 3 |
Altenkirch, Triguero; O’Neill |
\(H_n>10\) |
a lazy pipeline of |
part 3 |
|
a million copies of |
|
Lecture 1, §1.4; IEEE 754 |
|
|
the data structure determines the complexity |
part 4 |
Lecture 8, §8.3 |
last digits of consecutive primes |
|
part 4 |
|
|
a hidden quadratic cost |
part 4 |
Altenkirch, Triguero |
\(10^{16}-1\) |
|
part 4 |
Lecture 1 |
|
modular exponentiation instead of a huge power |
part 4 |
|
Horner’s scheme on an array |
the same function on an array, the same bits |
Lecture 5, §5.1 |
|
Newton basins |
vectorization over the starting points |
part 5 |
Lecture 5, §5.2 |
the Game of Life |
|
part 5 |
Lab 8 |
\(25!\) in NumPy |
integer overflow without a warning |
part 5 |
the instructor’s study; Lecture 1 |
the sum of all pairwise distances |
a formula after sorting instead of an \(n\times n\) matrix |
part 5 |
|
Gaussian elimination |
LAPACK; the advantage grows with the size |
Lecture 6, §6.1 |
|
checking \(Ax=b\) |
checking is cheaper than computing |
part 6 |
Lectures 3, 5, 6 |
bisection vs. |
fewer evaluations of an expensive function |
part 6 |
Lecture 5, §5.1 |
the barycentric form |
\(O(n)\) operations per point instead of \(O(n^2)\) |
part 6 |
Lecture 5, §5.3 |
the trapezoidal rule vs. |
machine precision after a few dozen function values |
part 6 |
Lecture 5, §5.4; Lab 7 |
\(\sin(x+1)+\cos(x+1)\) at a thousand points |
from |
Lecture 3, §3.4 |
|
|
polynomials without expression trees |
part 7 |
Lecture 3, §3.3 |
|
a decision procedure instead of a heuristic |
part 7 |
Lecture 5, §5.3; Richardson’s theorem |
\(H_{2000}\) exactly |
binary splitting; |
part 7 |
|
|
correctness pitfalls |
Lecture 6 |
|
the double loop from part 1 in Numba |
the compiler itself turns the loops into the formula \(n^2(n-1)\) |
Lecture 1, §1.2 |
|
Collatz steps for \(n\le10^7\) |
a loop that cannot be vectorized; compilation and a table of known results |
part 9 |
Lecture 1, Lab 8 |
Gaussian elimination in Numba |
compilation does not replace LAPACK |
part 9 |
Lecture 6, §6.1 |
\(21!\) and a million copies of |
64-bit integers; |
part 9 |
Lecture 1; IEEE 754 |
threads, processes, and |
the global interpreter lock (GIL), the cost of starting processes, performance and efficiency cores |
part 9 |
the instructor’s study |
How to read this chapter#
Lecture 1 and basic Python are enough. The parts can be read independently. Part 1 describes the measuring tool
porownaj, which parts 2–7 and 9 use.The chapter uses examples from the whole semester, including lectures that are still to come. Such an example is worth revisiting after the corresponding lecture.
The timings come from the computer on which the page was built (the line describing it at the beginning of each part), and they change with every build. What matters are the ratios of times and how the time grows with the size of the data. Differences of a few percent are noise.
The notebooks can be downloaded and run on your own computer (the button at the top of the page). You need NumPy, SciPy, SymPy, and Matplotlib, and for part 9 also Numba (
pip install numba). One comparison in part 7 also uses the MiniCAS package from Lecture 3.