Skip to main content

7.7b Matrix-speed labs

Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §7.7–7.7.2. Rewritten as original drills (list sandbox — no NumPy). Continues 7.7 Speeding up matrix computing.

Practice vector-style list ops, stride-aware nestings, and both matmul loop orders. Graded outputs lock correctness (same sums / same CC / same derivatives). Use time.perf_counter() locally to feel the speed gap — wall-clock is too noisy to grade.

Formula refresh​

Warm up: pick the matching equation among lookalikes (same walk as the theory lesson).

Labs​

Activity: Elementwise map via comprehension

Read five integers on one line. Apply f(x)=x2−3x+4f(x)=x^{2}-3x+4 to each (prefer a list comprehension). Print the five results as integers, space-separated.

Write-ups​

0/4 solved
7.7b.W1

Using “perf_counter”, “median”, and “noise”, explain:

How should you time two short kernels fairly?

Minimum 3 words. Your answer must include: “perf_counter”, “median”, “noise”.

0 words/ 3 min

Meet the writing requirements, then you can open the model answer.

Explorers​

# matrix_speed_ref.py — stride / matmul nestings (original sketch)
import time

def sos_row(M):
return sum(M[i][j] * M[i][j] for i in range(len(M)) for j in range(len(M[0])))

def sos_col(M):
n, m = len(M), len(M[0])
return sum(M[i][j] * M[i][j] for j in range(m) for i in range(n))

def time_call(fn, *args, repeats=5):
samples = []
for _ in range(repeats):
t0 = time.perf_counter()
fn(*args)
samples.append(time.perf_counter() - t0)
samples.sort()
return samples[len(samples) // 2]

Time sos_row vs sos_col (and both matmul nestings) for growing NN on your machine.

Next: 7.8 Code-listing sketches — original Newton / hyperfine sketches (not textbook dumps).