Operation Counts and Efficiency
How long will a computation take when the problem gets ten times bigger? For dense linear algebra the answer comes from counting floating-point operations. This lesson counts the flops of LU factorization, checks the prediction with timings, and explains why real libraries run far faster than the same flop count in a naive loop.
Counting LU
At step of elimination we update an block, one multiply and one subtract per entry:
| Task | Flops (leading term) |
|---|---|
| dot product, vector update | |
| matrix-vector product | |
| triangular solve | |
| LU factorization | |
| Cholesky (SPD matrices) | |
| matrix-matrix product | |
| explicit inverse |
Asymptotic notation. We write when , and when the ratio stays bounded. Only the leading term matters for large .
Checking the law
Timings are noisy, so instead of seconds we look at the growth factor when doubles, which should approach for LU. Measurements on small sizes are dominated by overhead, so the measured ratio grows towards 8 only as increases. The example prints the flop counts, which are exact; the measured ratio depends on your device, so it is left as a commented line to try.
import time
import numpy as np
from scipy.linalg import lu_factor
rng = np.random.default_rng(1)
def best_time(n, reps=3):
A = rng.normal(size=(n, n))
best = np.inf
for _ in range(reps):
t = time.perf_counter(); lu_factor(A); best = min(best, time.perf_counter() - t)
return best
flops = lambda n: 2 / 3 * n**3
print(f"flops n=300: {flops(300):.2e}, n=600: {flops(600):.2e}, ratio: {flops(600) / flops(300):.0f}")
# Measured on your device (typically between 3 and 12):
# print(f"time ratio: {best_time(600) / best_time(300):.1f}")flops n=300: 1.80e+07, n=600: 1.44e+08, ratio: 8
Flops are not the whole story
Modern CPUs can do dozens of flops in the time it takes to fetch one number from main memory. Algorithms are therefore limited either by arithmetic or by memory traffic:
- Matrix-vector products do flops on numbers: 2 flops per number loaded, memory-bound.
- Matrix-matrix products do flops on numbers: flops per number, compute-bound if organized in cache-sized blocks.
That is why LAPACK rewrites LU in blocked form, so that most of its work is matrix-matrix products (BLAS level 3). The loop-based LU of the previous lesson does the same flops but is hundreds of times slower.
import time
import numpy as np
from scipy.linalg import lu_factor
def lu_python(A):
U = A.copy(); n = len(U)
for k in range(n - 1):
m = U[k + 1:, k] / U[k, k]
U[k + 1:, k:] -= np.outer(m, U[k, k:])
return U
rng = np.random.default_rng(2)
A = rng.normal(size=(300, 300)) + 30 * np.eye(300)
lu, piv = lu_factor(A)
U = lu_python(A)
print("same U factor (no row swaps needed):", np.allclose(np.triu(lu), np.triu(U)), (piv == np.arange(300)).all())
print(f"flops: {2 / 3 * 300**3:.2e}")
# Timings depend on the device; uncomment to compare (LAPACK is usually many times faster):
# t = time.perf_counter(); lu_python(A); t_py = time.perf_counter() - t
# t = time.perf_counter(); lu_factor(A); t_lapack = time.perf_counter() - t
# print(f"NumPy loop / LAPACK time: {t_py / t_lapack:.0f}x")same U factor (no row swaps needed): True True
flops: 1.80e+07
Sparse and structured matrices
The count assumes a dense matrix. Banded, sparse and structured matrices can be factorized much more cheaply: a tridiagonal system costs (Banded and Positive Definite Matrices), and large sparse systems from PDEs are often solved iteratively (Sparse Matrices).
In software
- NumPy's speed depends on its BLAS: OpenBLAS, Intel MKL, Apple Accelerate.
np.show_config()shows which one is used. - GPU libraries (cuBLAS, cuSOLVER) do the same blocked algorithms with thousands of cores; the scaling is unchanged.
Exercises
Exercise 1: Predict the time
LU of a matrix takes 1.2 s. Predict the time for .
Answer
About 32 s.
Solution
times longer: s.
Exercise 2: Exact count
Compute exactly and check its leading term.
Answer
.
Solution
With , . The leading term is .
Exercise 3: Count with code (code)
Instrument lu_python to count multiplications and subtractions (count the size of each update) for and divide by .
Answer
The ratio approaches 1: about , , (the lower-order terms fade).
Solution
At step (0-based) the update touches entries with 2 flops each, plus divisions.
for n in (10, 100, 1000):
flops = sum(2 * (n - k - 1) * (n - k) + (n - k - 1) for k in range(n - 1))
print(n, round(flops / (2 / 3 * n**3), 4))10 1.0575
100 1.0073
1000 1.0007
Test yourself
LU factorization of a dense matrix costs about…
- flops
- flops
- flops
- flops
Doubling multiplies the time of an algorithm by about…
- 2
- 4
- 8
- 16
Why are blocked algorithms faster at the same flop count?
- They do fewer flops
- They reuse data in cache, reducing memory traffic
- They use lower precision
- They skip zeros