Part 8. Cheat sheet: good practice and pitfalls#
This part gathers the conclusions of the whole chapter into a single checklist: the order of decisions when speeding up a program. To it we add the correctness pitfalls that occur most often in mathematical code. They are not about time, but about a program silently computing something other than what we wanted. At the end there is a summary of part 9 on compilation and parallel computing, and the references.
The Zen of Python#
The principles of Python’s style were written down by Tim Peters in PEP 20. Python prints them
when you import the module this:
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Three of them came up most often in this chapter: simplicity (“Simple is better than complex”), readability (“Readability counts”), and explicit errors (“Errors should never pass silently”). Pythonic laziness is not about writing less careful code, but about writing less code: ready-made functions are shorter, faster, and better tested than ours.
The ladder of laziness: the order of decisions#
When a program runs too slowly, we go through the rungs one by one. The higher rungs usually give orders of magnitude, the lower ones percentages.
Contract and checker. Decide what the program is supposed to compute, and write a simple test or a checker for the result. Compare every faster version with the slow one (part 1).
Measure and profile. Speed up only what really takes time.
%timeit,timeit,cProfile(part 1).Mathematics. Can we avoid computing altogether? A formula instead of a loop, a better parametrization, symmetry (part 2).
Algorithm and data structure. A cache for recursion, a set instead of a list, a heap instead of sorting, a good search order (parts 2 and 4).
A ready-made function. Built-in functions,
math,itertools,collections, SciPy, specialized SymPy functions (parts 4, 6, and 7).Vectorization. Loops over independent data are moved to NumPy (part 5). Symbolic computation is done once and turned into a numerical function (
lambdify, part 7).Lazy evaluation. Generators and
any/allstop working once they know the answer, and they do not keep everything in memory (part 3).Small fixes. Code in functions rather than in a cell, a list comprehension instead of
append,joininstead of concatenating strings. They give percentages, sometimes a several-fold speedup, but not orders of magnitude (part 1).Only then compilation and parallel computing: Numba, processes, threads without the global interpreter lock (part 9).
In 1974 D. E. Knuth wrote that premature optimization is the root of all evil, but he added that we should not pass up the few percent of the code that really determine the running time. The profiler is there to find them.
Correctness pitfalls in mathematical code#
A matrix from [[0] * n] * n. Multiplying a list by a number duplicates the references,
not the rows. All the rows of such a “matrix” are the same object:
zla = [[0] * 3] * 3
zla[0][0] = 1
print("[[0] * 3] * 3 po zmianie jednego elementu:", zla)
dobra = [[0] * 3 for _ in range(3)]
dobra[0][0] = 1
print("lista składana po zmianie jednego elementu:", dobra)
[[0] * 3] * 3 po zmianie jednego elementu: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
lista składana po zmianie jednego elementu: [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
So we build matrices with a list comprehension, like the function hilbert in Lecture 6, or as
[[0] * m for _ in range(n)]. The multiplication [0] * m inside is safe, because numbers are
immutable.
A mutable default argument. The default value of an argument is created once, when the function is defined, not at every call. A list as a default value grows from call to call:
def dopisz_zle(x, lista=[]):
lista.append(x)
return lista
def dopisz(x, lista=None):
if lista is None:
lista = []
lista.append(x)
return lista
print(dopisz_zle(1), dopisz_zle(2), "|", dopisz(1), dopisz(2))
[1, 2] [1, 2] | [1] [2]
Both calls of dopisz_zle returned the same list object, which after the second call contains
both numbers. The safe pattern is the default value None and a new list created inside the
function.
Comparing float numbers. We know from Lecture 1 that 0.1 + 0.2 != 0.3. For comparisons
there is math.isclose. It has its own pitfall, however: by default it uses only a relative
tolerance, and relative to zero every nonzero number is “far away”:
import math
print("0.1 + 0.2 == 0.3:", 0.1 + 0.2 == 0.3)
print("math.isclose(0.1 + 0.2, 0.3):", math.isclose(0.1 + 0.2, 0.3))
r = math.sin(math.pi) # matematycznie 0
print(f"sin(pi) = {r!r}")
print("math.isclose(sin(pi), 0):", math.isclose(r, 0))
print("math.isclose(sin(pi), 0, abs_tol=1e-12):",
math.isclose(r, 0, abs_tol=1e-12))
0.1 + 0.2 == 0.3: False
math.isclose(0.1 + 0.2, 0.3): True
sin(pi) = 1.2246467991473532e-16
math.isclose(sin(pi), 0): False
math.isclose(sin(pi), 0, abs_tol=1e-12): True
When comparing with zero, you have to give an absolute tolerance abs_tol. Its value depends on
the scale of the problem, so we choose it deliberately.
is instead of ==. The operator is checks whether two things are the same object, not
whether their values are equal. CPython keeps permanent objects for small integers (from \(-5\) to
\(256\)), so for them is happens to “work”:
a, b = int("100"), int("100")
c, d = int("1000"), int("1000")
print("100 is 100:", a is b, " 1000 is 1000:", c is d,
" 1000 == 1000:", c == d)
100 is 100: True 1000 is 1000: False 1000 == 1000: True
We use the operator is only with None, True, and False. Numbers and other values are
compared with the operator ==.
Late binding in functions created in a loop. A lambda function remembers the variable,
not its value at the moment of creation. A list of functions \(t\mapsto t^k\) built in a loop gives
nothing but \(t^3\):
potegi_zle = [lambda t: t**k for k in range(4)]
potegi = [lambda t, k=k: t**k for k in range(4)] # k zapisane w argumencie
print("zła lista w t = 2: ", [f(2) for f in potegi_zle])
print("dobra lista w t = 2:", [f(2) for f in potegi])
zła lista w t = 2: [8, 8, 8, 8]
dobra lista w t = 2: [1, 2, 4, 8]
This pitfall lies in wait, for example, when building the Lagrange basis functions as a list of
lambda functions. In Lecture 5 we created them as SymPy expressions and turned them into
functions only with lambdify, so the problem did not arise.
A function parameter vs. modifying a list. Assigning to a parameter does not change the variable that was passed to the function. Changing the contents of a list, on the other hand, changes it outside as well. Altenkirch and Triguero describe this as one of the “mysteries of Python”:
def normuj_nowa(v):
s = sum(v)
v = [x / s for x in v] # nowa lista; v na zewnątrz bez zmian
def normuj_w_miejscu(v):
s = sum(v)
v[:] = [x / s for x in v] # zmiana zawartości przekazanej listy
w = [1, 1, 2]
normuj_nowa(w)
print("po normuj_nowa: ", w)
normuj_w_miejscu(w)
print("po normuj_w_miejscu:", w)
po normuj_nowa: [1, 1, 2]
po normuj_w_miejscu: [0.25, 0.25, 0.5]
The most readable is a third way: the function returns a new result (return [x / s for x in v])
and changes nothing in place. That is why the function eliminacja from Lecture 6 starts by
copying the matrix into a new list M.
Reproducibility. Results that involve random draws repeat only with a fixed seed. In
Lecture 5 the Monte Carlo method uses np.random.default_rng(20261202). A generator of your own
(random.Random(ziarno), np.random.default_rng(ziarno)) is better than setting the global
seed, because other parts of the program will not reset it.
import random
import numpy as np
print("random.Random(1) trzy razy:",
[random.Random(1).randrange(100) for _ in range(3)])
print("dwa generatory z ziarnem 7:",
np.random.default_rng(7).integers(0, 100, 3),
np.random.default_rng(7).integers(0, 100, 3))
random.Random(1) trzy razy: [17, 17, 17]
dwa generatory z ziarnem 7: [94 62 68] [94 62 68]
The first line shows one more pitfall: every call of random.Random(1) creates a new
generator, so it draws the same number three times. We create the generator once and then draw
from it.
Readable code#
Functions instead of code in a cell. They are faster (part 1), and they can be tested and reused. One function performs one task, and a short documentation string (docstring) describes what it does.
Names say what they mean.
kroki_collatza(n)instead off(n),wezly_czebyszewainstead ofw. In the course materials names are in Polish, without Polish diacritics, consistently throughout the program.Check your assumptions.
assertin the code and a comparison with the slow version (porownaj) catch errors before we start measuring time. A simple checker verifies the result of the fast program.No global state. A function that reads and modifies global variables is hard to test and cannot be safely memoized (part 2). The global counters in this chapter serve only to show how much work a program did.
Style according to PEP 8. Spaces around operators, indentation with four spaces, lines no longer than \(79\) characters. Tools such as
rufforblackformat code automatically.
Compilation and parallel computing in brief#
The measurements and the details are in part 9.
Numba (the
njitdecorator) compiles functions on numbers and NumPy arrays. It helps most with loops that cannot be vectorized, for example when each element needs a different number of steps. The first call includes the compilation.Compilation does not change the algorithm. A ready-made library such as LAPACK can still be many times faster than a compiled loop.
In compiled code integers have 64 bits, and the option
fastmath=Trueallows the compiler to change the result of computations onfloatnumbers.Threads do not speed up pure Python, because the global interpreter lock (GIL) lets only one of them compute at a time. Processes do speed it up, but they have to be started and sent the data, and the function they execute must be defined in a module.
A
prangeloop in Numba divides the iterations among threads that do not need the lock. The iterations must be independent of one another.The speedup from several cores is at most the number of cores (Amdahl’s law). A better algorithm on one core often beats a worse one on all of them.
References#
T. Altenkirch, I. Triguero, Conceptual Programming with Python, Lulu.com 2020. The lazy sieve, recursive binomial coefficients, sudoku by backtracking, the Collatz sequence with
yield.The instructor’s study Python Performance: From Bytecode to CPU Cores (2026, in English): a loop vs. a generator, variable scope, measuring time, memory, processes and threads, compilation.
Python documentation: the modules
timeit,dis,cProfile,functools,itertools,collections,heapq,bisect,math; PEP 8 (style), PEP 20 (the Zen of Python), PEP 659 (the specializing interpreter), PEP 703 (CPython without the GIL).C. R. Harris et al., Array programming with NumPy, Nature 585 (2020).
P. Virtanen et al., SciPy 1.0: fundamental algorithms for scientific computing in Python, Nature Methods 17 (2020).
A. Meurer et al., SymPy: symbolic computing in Python, PeerJ Computer Science 3 (2017).
M. Gorelick, I. Ozsvald, High Performance Python, 2nd ed., O’Reilly 2020.
M. E. O’Neill, The Genuine Sieve of Eratosthenes, Journal of Functional Programming 19 (2009).
P. Norvig, Solving Every Sudoku Puzzle (an essay on the author’s website).
J.-P. Berrut, L. N. Trefethen, Barycentric Lagrange Interpolation, SIAM Review 46 (2004).
R. J. Lemke Oliver, K. Soundararajan, Unexpected biases in the distribution of consecutive primes, PNAS 113 (2016).
B. Haible, T. Papanikolaou, Fast multiprecision evaluation of series of rational numbers, ANTS-III, LNCS 1423 (1998).
D. E. Knuth, Structured Programming with go to Statements, Computing Surveys 6 (1974).
Exercises#
★ Go through your solutions to the lab exercises. Find in them
[[0] * n] * n,l = l + [x]in a loop,subsin a loop, and comparisons offloatnumbers with the operator==. Fix them.★★ Choose the slowest function among your lab solutions. Profile it (
cProfile), propose a faster version, check that the results agree, and measure the speedup with the functionporownaj. Describe which rung of the ladder of laziness worked.★★ Write a function
bazowe_lagrange(X)that returns the list of functions \(\ell_i\) aslambdafunctions. Check that \(\ell_i(x_j)=\delta_{ij}\). Deliberately make the late-binding mistake and see how it shows up in this test.★★★ Project: compute the Collatz steps for all \(n\le10^6\) in NumPy, advancing all the trajectories at once (with a mask of the numbers that have already reached \(1\)). Compare this version with the versions from part 9. Why does NumPy help so little here?