TExcelTAD
Home › Numerical Methods › Operation Counts and Efficiency

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 kk of elimination we update an (n−k)×(n−k)(n - k) \times (n - k) block, one multiply and one subtract per entry:

∑k=1n−12(n−k)2≈2⋅n33=23n3 flops.\sum_{k=1}^{n-1}2(n - k)^2 \approx 2\cdot\frac{n^3}{3} = \frac{2}{3}n^3 \text{ flops}.
Task Flops (leading term)
dot product, vector update 2n2n
matrix-vector product 2n22n^2
triangular solve n2n^2
LU factorization 23n3\frac{2}{3}n^3
Cholesky (SPD matrices) 13n3\frac{1}{3}n^3
matrix-matrix product 2n32n^3
explicit inverse 2n32n^3

Asymptotic notation. We write f(n)∼g(n)f(n) \sim g(n) when f(n)g(n)→1\frac{f(n)}{g(n)} \to 1, and f(n)=O(g(n))f(n) = O(g(n)) when the ratio stays bounded. Only the leading term matters for large nn.

Checking the n3n^3 law

Timings are noisy, so instead of seconds we look at the growth factor when nn doubles, which should approach 23=82^3 = 8 for LU. Measurements on small sizes are dominated by overhead, so the measured ratio grows towards 8 only as nn 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.

python · try it yourself
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 2n22n^2 flops on n2n^2 numbers: 2 flops per number loaded, memory-bound.
  • Matrix-matrix products do 2n32n^3 flops on 3n23n^2 numbers: O(n)O(n) 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.

python · try it yourself
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 23n3\frac{2}{3}n^3 count assumes a dense matrix. Banded, sparse and structured matrices can be factorized much more cheaply: a tridiagonal system costs O(n)O(n) (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 n3n^3 scaling is unchanged.

Exercises

Exercise 1: Predict the time

LU of a 5000×50005000 \times 5000 matrix takes 1.2 s. Predict the time for n=15000n = 15000.

Answer

About 32 s.

Solution

33=273^3 = 27 times longer: 1.2×27=32.41.2 \times 27 = 32.4 s.

Exercise 2: Exact count

Compute ∑k=1n−12(n−k)2\sum_{k=1}^{n-1}2(n - k)^2 exactly and check its leading term.

Answer

(n−1)n(2n−1)3=23n3−n2+n3\frac{(n - 1)n(2n - 1)}{3} = \frac{2}{3}n^3 - n^2 + \frac{n}{3}.

Solution

With j=n−kj = n - k, 2∑j=1n−1j2=2⋅(n−1)n(2n−1)62\sum_{j=1}^{n-1}j^2 = 2\cdot\frac{(n - 1)n(2n - 1)}{6}. The leading term is 23n3\frac{2}{3}n^3.

Exercise 3: Count with code (code)

Instrument lu_python to count multiplications and subtractions (count the size of each update) for n=10,100,1000n = 10, 100, 1000 and divide by 23n3\frac{2}{3}n^3.

Answer

The ratio approaches 1: about 1.0581.058, 1.0071.007, 1.00071.0007 (the lower-order terms fade).

Solution

At step kk (0-based) the update touches (n−k−1)(n−k)(n - k - 1)(n - k) entries with 2 flops each, plus n−k−1n - k - 1 divisions.

python · try it yourself
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 n×nn \times n matrix costs about…

  1. n2n^2 flops
  2. 23n3\frac{2}{3}n^3 flops
  3. 2n32n^3 flops
  4. nlog⁡nn\log n flops

Doubling nn multiplies the time of an O(n3)O(n^3) algorithm by about…

  1. 2
  2. 4
  3. 8
  4. 16

Why are blocked algorithms faster at the same flop count?

  1. They do fewer flops
  2. They reuse data in cache, reducing memory traffic
  3. They use lower precision
  4. They skip zeros