Mini Project: An Empirical Growth-Rate Profiler
Theory predicts that insertion sort makes about shifts on random input and that merge sort makes about comparisons. In this project you build a small tool that checks such predictions empirically: it runs an algorithm on inputs of growing size, counts its steps, and fits the counts to the standard growth functions. Given an unknown function, it tells you its likely order of growth and the constant in front.
The profiler counts steps instead of measuring seconds, for the reasons from the RAM model: counts are exact, repeatable and independent of the machine. Every input is generated from a fixed seed, so you get exactly the output shown. Each step below is a complete program; later steps repeat the pieces they need, so you can run any of them on its own.
Step 1: Instrumented algorithms
An algorithm reports its work through a counter object. The convention: call c.tick() once per basic operation, which you choose per algorithm (a comparison for sorting and searching, an innermost-loop body for nested loops).
class StepCounter:
def __init__(self):
self.steps = 0
def tick(self, k=1):
self.steps += k
def insertion_sort(a, c):
a = list(a)
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0:
c.tick() # one key comparison
if a[j] <= key:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
def merge_sort(a, c):
if len(a) <= 1:
return list(a)
mid = len(a) // 2
left, right = merge_sort(a[:mid], c), merge_sort(a[mid:], c)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
c.tick() # one key comparison
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
data = [7, 3, 8, 5, 2, 6, 1, 4]
for algo in [insertion_sort, merge_sort]:
c = StepCounter()
result = algo(data, c)
print(f"{algo.__name__:>14}: {result}, {c.steps} comparisons")insertion_sort: [1, 2, 3, 4, 5, 6, 7, 8], 23 comparisons
merge_sort: [1, 2, 3, 4, 5, 6, 7, 8], 16 comparisons
In C++
The same two instrumented sorts in C++, with StepCounter as a small struct:
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
struct StepCounter {
long steps = 0;
void tick(long k = 1) { steps += k; }
};
vector<int> insertion_sort(const vector<int>& input, StepCounter& c) {
vector<int> a = input;
for (int i = 1; i < (int)a.size(); i++) {
int key = a[i], j = i - 1;
while (j >= 0) {
c.tick(); // one key comparison
if (a[j] <= key) break;
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
return a;
}
vector<int> merge_sort(const vector<int>& a, StepCounter& c) {
if (a.size() <= 1) return a;
size_t mid = a.size() / 2;
vector<int> left = merge_sort(vector<int>(a.begin(), a.begin() + mid), c);
vector<int> right = merge_sort(vector<int>(a.begin() + mid, a.end()), c);
vector<int> out;
size_t i = 0, j = 0;
while (i < left.size() && j < right.size()) {
c.tick(); // one key comparison
if (left[i] <= right[j]) out.push_back(left[i++]);
else out.push_back(right[j++]);
}
out.insert(out.end(), left.begin() + i, left.end());
out.insert(out.end(), right.begin() + j, right.end());
return out;
}
string show(const vector<int>& a) {
string s = "[";
for (size_t k = 0; k < a.size(); k++) s += (k ? ", " : "") + to_string(a[k]);
return s + "]";
}
int main() {
vector<int> data = {7, 3, 8, 5, 2, 6, 1, 4};
struct Algo { const char* name; vector<int> (*sort)(const vector<int>&, StepCounter&); };
Algo algos[] = {{"insertion_sort", insertion_sort}, {"merge_sort", merge_sort}};
for (const Algo& algo : algos) {
StepCounter c;
vector<int> result = algo.sort(data, c);
printf("%14s: %s, %ld comparisons\n", algo.name, show(result).c_str(), c.steps);
}
}insertion_sort: [1, 2, 3, 4, 5, 6, 7, 8], 23 comparisons
merge_sort: [1, 2, 3, 4, 5, 6, 7, 8], 16 comparisons
On just eight values merge sort already needs fewer comparisons (16 against 23), but counts this small say little. The profiler's job is to show what happens as grows.
Step 2: Measure over doubling sizes
measure runs an algorithm on inputs of sizes and returns the pairs . A doubling ratio near suggests growth like (Order of Growth), so the estimate of the exponent is .
import math, random
class StepCounter:
def __init__(self):
self.steps = 0
def tick(self, k=1):
self.steps += k
def insertion_sort(a, c):
a = list(a)
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0:
c.tick()
if a[j] <= key:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
def random_list(n, seed):
return random.Random(seed).sample(range(10 * n), n)
def measure(algo, make_input, sizes):
rows = []
for n in sizes:
c = StepCounter()
algo(make_input(n, seed=n), c)
rows.append((n, c.steps))
return rows
rows = measure(insertion_sort, random_list, [125, 250, 500, 1000, 2000])
for (n1, t1), (n2, t2) in zip(rows, rows[1:]):
print(f"n = {n2:>5}: {t2:>9,} steps, T(2n)/T(n) = {t2 / t1:.3f}, exponent estimate {math.log2(t2 / t1):.3f}")n = 250: 17,233 steps, T(2n)/T(n) = 4.630, exponent estimate 2.211
n = 500: 64,481 steps, T(2n)/T(n) = 3.742, exponent estimate 1.904
n = 1000: 246,027 steps, T(2n)/T(n) = 3.815, exponent estimate 1.932
n = 2000: 979,956 steps, T(2n)/T(n) = 3.983, exponent estimate 1.994
The exponent estimates scatter between 1.90 and 2.21 around the true value 2. Random inputs add noise, so a single ratio can be off by 10 percent; the next step uses all the measurements at once.
Step 3: Fit candidate models
A doubling ratio cannot tell from well: their ratios are and , which differ by only a few percent at practical sizes. A better approach tries each candidate from a list and fits .
For a fixed , choose to minimise the squared relative errors . Writing , the minimum is at
and the candidate whose fit has the smallest error wins. Relative errors keep the largest from dominating the fit. Exponential models are left out: at , is too large for a Python float, and an exponential algorithm could not be run at such sizes anyway.
import math
MODELS = {
"1": lambda n: 1.0,
"lg n": lambda n: math.log2(n),
"n": lambda n: float(n),
"n lg n": lambda n: n * math.log2(n),
"n^2": lambda n: float(n * n),
"n^3": lambda n: float(n ** 3),
}
def fit(rows, g):
r = [g(n) / t for n, t in rows]
C = sum(r) / sum(x * x for x in r)
err = math.sqrt(sum((1 - C * x) ** 2 for x in r) / len(r))
return C, err
def best_models(rows, top=3):
fits = sorted(((fit(rows, g)[1], name, fit(rows, g)[0]) for name, g in MODELS.items()))
return fits[:top]
# three exact step counts with known answers
tests = {
"3n + 5": [(n, 3 * n + 5) for n in [64, 128, 256, 512, 1024]],
"n(n-1)/2": [(n, n * (n - 1) // 2) for n in [64, 128, 256, 512, 1024]],
"n lg n - n + 1 (merge)": [(n, n * int(math.log2(n)) - n + 1) for n in [64, 128, 256, 512, 1024]],
}
for name, rows in tests.items():
ranked = ", ".join(f"{m} (C = {C:.3f}, error {e:.1%})" for e, m, C in best_models(rows))
print(f"{name:>22}: {ranked}") 3n + 5: n (C = 3.030, error 0.9%), n lg n (C = 0.366, error 18.1%), lg n (C = 48.383, error 58.6%)
n(n-1)/2: n^2 (C = 0.497, error 0.5%), n lg n (C = 7.746, error 59.3%), n^3 (C = 0.001, error 66.0%)
n lg n - n + 1 (merge): n lg n (C = 0.871, error 2.6%), n (C = 6.431, error 20.6%), n^2 (C = 0.013, error 59.2%)
Each known count is identified correctly, and recovers the leading coefficient: about 3 for and about for . For merge sort's worst case, , the fitted is below 1 because the term is still significant at these sizes; it creeps towards 1 as grows. Lower-order terms are exactly where empirical fits are weakest.
Step 4: The complete profiler
Put the pieces together: profile measures an algorithm over doubling sizes, prints the counts and doubling ratios, and reports the best model with its constant. Run it on the two sorts with random inputs.
import math, random
class StepCounter:
def __init__(self):
self.steps = 0
def tick(self, k=1):
self.steps += k
def insertion_sort(a, c):
a = list(a)
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0:
c.tick()
if a[j] <= key:
break
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
def merge_sort(a, c):
if len(a) <= 1:
return list(a)
mid = len(a) // 2
left, right = merge_sort(a[:mid], c), merge_sort(a[mid:], c)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
c.tick()
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]
MODELS = {
"1": lambda n: 1.0, "lg n": lambda n: math.log2(n), "n": lambda n: float(n),
"n lg n": lambda n: n * math.log2(n), "n^2": lambda n: float(n * n),
"n^3": lambda n: float(n ** 3),
}
def fit(rows, g):
r = [g(n) / t for n, t in rows]
C = sum(r) / sum(x * x for x in r)
return C, math.sqrt(sum((1 - C * x) ** 2 for x in r) / len(r))
def random_list(n, seed):
return random.Random(seed).sample(range(10 * n), n)
def profile(algo, make_input=random_list, start=64, doublings=5):
rows = []
n = start
for _ in range(doublings):
c = StepCounter()
algo(make_input(n, seed=n), c)
rows.append((n, c.steps))
n *= 2
print(f"{algo.__name__}")
prev = None
for n, t in rows:
ratio = f" ratio {t / prev:.2f}" if prev else ""
print(f" n = {n:>5}: {t:>9,} steps{ratio}")
prev = t
err, name, C = min((fit(rows, g)[1], name, fit(rows, g)[0]) for name, g in MODELS.items())
print(f" best fit: {C:.3f} * {name} (relative error {err:.1%})")
profile(insertion_sort)
profile(merge_sort)insertion_sort
n = 64: 1,032 steps
n = 128: 4,185 steps ratio 4.06
n = 256: 16,815 steps ratio 4.02
n = 512: 68,555 steps ratio 4.08
n = 1024: 261,302 steps ratio 3.81
best fit: 0.255 * n^2 (relative error 1.6%)
merge_sort
n = 64: 308 steps
n = 128: 744 steps ratio 2.42
n = 256: 1,710 steps ratio 2.30
n = 512: 3,956 steps ratio 2.31
n = 1024: 8,903 steps ratio 2.25
best fit: 0.838 * n lg n (relative error 2.8%)
The profiler reproduces the theory: insertion sort on random input is about , matching the average derived in Counting Steps Exactly, and merge sort is about . Merge sort's ratios sit a little above 2 and slowly fall, the signature of .
Step 5: Profile some mystery functions
Now use the tool on code whose cost you have not derived. Before running, guess each answer from the code.
import math
class StepCounter:
def __init__(self):
self.steps = 0
def tick(self, k=1):
self.steps += k
MODELS = {
"1": lambda n: 1.0, "lg n": lambda n: math.log2(n), "n": lambda n: float(n),
"n lg n": lambda n: n * math.log2(n), "n^2": lambda n: float(n * n),
"n^3": lambda n: float(n ** 3),
}
def fit(rows, g):
r = [g(n) / t for n, t in rows]
C = sum(r) / sum(x * x for x in r)
return C, math.sqrt(sum((1 - C * x) ** 2 for x in r) / len(r))
def mystery_a(n, c): # a loop whose step doubles
i = 1
while i < n:
c.tick()
i *= 2
def mystery_b(n, c): # nested loop, inner bound i*i
i = 1
while i * i <= n:
for _ in range(i):
c.tick()
i += 1
def mystery_c(n, c): # halving recursion with a full scan
if n <= 1:
c.tick()
return
c.tick(n)
mystery_c(n // 2, c)
mystery_c(n // 2, c)
def mystery_d(n, c): # all pairs inside a doubling loop
size = 1
while size <= n:
for i in range(size):
for j in range(i):
c.tick()
size *= 2
for f in [mystery_a, mystery_b, mystery_c, mystery_d]:
rows = []
for n in [256, 512, 1024, 2048, 4096]:
c = StepCounter()
f(n, c)
rows.append((n, c.steps))
err, name, C = min((fit(rows, g)[1], name, fit(rows, g)[0]) for name, g in MODELS.items())
counts = ", ".join(str(t) for _, t in rows)
print(f"{f.__name__}: {counts}\n best fit {C:.3f} * {name} (error {err:.1%})")mystery_a: 8, 9, 10, 11, 12
best fit 1.000 * lg n (error 0.0%)
mystery_b: 136, 253, 528, 1035, 2080
best fit 0.510 * n (error 2.4%)
mystery_c: 2304, 5120, 11264, 24576, 53248
best fit 1.102 * n lg n (error 1.3%)
mystery_d: 43435, 174251, 698027, 2794155, 11180715
best fit 0.665 * n^2 (error 0.2%)
In C++
The core of the profiler in C++: the step counter, the models, the fit and the four mystery functions. The counts are exact, so the output matches the Python version line by line:
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
struct StepCounter {
long steps = 0;
void tick(long k = 1) { steps += k; }
};
struct Model { const char* name; double (*g)(double); };
const Model MODELS[] = {
{"1", [](double) { return 1.0; }},
{"lg n", [](double n) { return log2(n); }},
{"n", [](double n) { return n; }},
{"n lg n", [](double n) { return n * log2(n); }},
{"n^2", [](double n) { return n * n; }},
{"n^3", [](double n) { return n * n * n; }},
};
struct Row { long n, t; };
struct Fit { double C, err; };
Fit fit(const vector<Row>& rows, double (*g)(double)) {
vector<double> r;
for (const Row& row : rows) r.push_back(g(row.n) / row.t);
double sum = 0, sum_sq = 0;
for (double x : r) { sum += x; sum_sq += x * x; }
double C = sum / sum_sq, sq_err = 0;
for (double x : r) sq_err += (1 - C * x) * (1 - C * x);
return {C, sqrt(sq_err / r.size())};
}
void mystery_a(long n, StepCounter& c) { // a loop whose step doubles
for (long i = 1; i < n; i *= 2) c.tick();
}
void mystery_b(long n, StepCounter& c) { // nested loop, inner bound i*i
for (long i = 1; i * i <= n; i++)
for (long k = 0; k < i; k++) c.tick();
}
void mystery_c(long n, StepCounter& c) { // halving recursion with a full scan
if (n <= 1) {
c.tick();
return;
}
c.tick(n);
mystery_c(n / 2, c);
mystery_c(n / 2, c);
}
void mystery_d(long n, StepCounter& c) { // all pairs inside a doubling loop
for (long size = 1; size <= n; size *= 2)
for (long i = 0; i < size; i++)
for (long j = 0; j < i; j++) c.tick();
}
int main() {
struct Mystery { const char* name; void (*f)(long, StepCounter&); };
const Mystery mysteries[] = {{"mystery_a", mystery_a}, {"mystery_b", mystery_b},
{"mystery_c", mystery_c}, {"mystery_d", mystery_d}};
for (const Mystery& m : mysteries) {
vector<Row> rows;
for (long n : {256, 512, 1024, 2048, 4096}) {
StepCounter c;
m.f(n, c);
rows.push_back({n, c.steps});
}
const Model* best = nullptr;
Fit best_fit{0, INFINITY};
for (const Model& model : MODELS) {
Fit f = fit(rows, model.g);
if (f.err < best_fit.err) { best = &model; best_fit = f; }
}
string counts;
for (const Row& row : rows) counts += (counts.empty() ? "" : ", ") + to_string(row.t);
printf("%s: %s\n best fit %.3f * %s (error %.1f%%)\n", m.name, counts.c_str(),
best_fit.C, best->name, 100 * best_fit.err);
}
}mystery_a: 8, 9, 10, 11, 12
best fit 1.000 * lg n (error 0.0%)
mystery_b: 136, 253, 528, 1035, 2080
best fit 0.510 * n (error 2.4%)
mystery_c: 2304, 5120, 11264, 24576, 53248
best fit 1.102 * n lg n (error 1.3%)
mystery_d: 43435, 174251, 698027, 2794155, 11180715
best fit 0.665 * n^2 (error 0.2%)
All four fits are what an analysis of the code predicts:
mystery_adoubles until it reaches : exactly steps for a power of 2.mystery_bruns its inner loop times for with , so it makes steps: 136 is and 253 is . A nested loop is not automatically quadratic; here the outer loop is short.mystery_csatisfies with , whose exact solution for powers of 2 is ; the extra pushes slightly above 1.mystery_dadds up for . The last term dominates and the others form a geometric series, .
A fit is evidence, not proof. If the best model's error is large, none of the candidates describes the counts, and you need either a new model or a closer look at the code.
Extensions
- A model that is missing. Profile trial division (count the divisions made to test the largest prime below ) and note which model wins and how large its error is. Then add to
MODELSand run it again: the error should drop sharply. - Add models. Put and in
MODELS, then profile the three-way recursion from Exercise 9 and check that it picks . - Best and worst case. Pass
make_inputfunctions that build sorted and reversed lists, and confirm insertion sort's linear best case and worst case. - Several trials. For randomized inputs, average the counts over five seeds per size before fitting, and watch the fitting error shrink.
Test yourself
Why does the profiler count steps instead of timing the functions?
- Timing is impossible in Python
- Counts are exact and identical on every machine and every run, so the fit reflects the algorithm and not system noise
- Counts are always smaller
- Timing would make the code longer
Why is the doubling ratio alone a weak way to tell from ?
- Because both ratios are exactly 2
- Because the ratios are and , which differ by only a few percent at practical sizes
- Because has no doubling ratio
- Because grows faster
In the fit , why does the profiler minimise relative rather than absolute errors?
- Relative errors are faster to compute
- Otherwise the largest , whose counts are much bigger, would dominate the fit
- Absolute errors are always zero
- Because must be an integer