Asymptotic analysis
Measuring how cost grows: timing with ContinuousClock and doubling experiments, counting operations, the four simplifications, and the definitions of big Theta and big O.
- CS61B
- Asymptotics I · Textbook Ch. 11
- Swift book
- Control Flow
- Documentation
- ContinuousClock
Unit 4 built data structures and said, informally, which operations were fast. Unit 5 makes that precise. Lesson 18 introduced orders of growth with a table; this lesson, following CS61B’s asymptotics lectures, explains where the table comes from, how to derive an order of growth from code, and what the notation Θ(N²) actually claims.
CS61B distinguishes two costs of a program: the programming cost, how long it takes people to write and change it, and the execution cost, how much time and memory it uses when it runs. Unit 4 cared about both. This unit is about the second.
Two ways to find duplicates
Here are two functions that decide whether a sorted array contains a repeated value, CS61B’s running example:
/// Compares every pair.
func dup1(_ values: [Int]) -> Bool {
for i in 0..<values.count {
for j in (i + 1)..<values.count where values[i] == values[j] {
return true
}
}
return false
}
/// In a sorted array, equal values are next to each other.
func dup2(_ values: [Int]) -> Bool {
for i in 0..<(values.count - 1) where values[i] == values[i + 1] {
return true
}
return false
}
let sorted = [-3, -1, 2, 4, 4, 8, 10, 12]
print(dup1(sorted), dup2(sorted), dup1([1, 2, 3]), dup2([1, 2, 3])) // true true false false
dup2 is clearly better. The question is how to say by how much, in a way
that does not depend on the computer.
Measuring
The direct approach is to time them. ContinuousClock measures elapsed time,
and its measure method times a closure:
let clock = ContinuousClock()
let values = Array(0..<40_000) // no duplicates: the worst case
let elapsed = clock.measure {
_ = dup1(values)
}
print(elapsed)
Timing is only meaningful with an optimized build (swiftc -O, or
swift build -c release), since debug builds check and slow down everything,
and only when repeated a few times, keeping the fastest run. On the computer
this lesson was written on, the results were:
| N (items) | dup1 |
dup2 |
|---|---|---|
| 10,000 | 21 ms | 0.005 ms |
| 20,000 | 61 ms | 0.008 ms |
| 40,000 | 240 ms | 0.016 ms |
| 80,000 | 962 ms | 0.032 ms |
The absolute numbers depend on the machine. The ratios do not: each time
N doubles, dup1 takes about four times as long, and dup2 about twice as
long. This doubling experiment is a practical way to estimate how a
function’s cost grows: if doubling the input multiplies the time by 2ᵏ, the cost
grows roughly like Nᵏ.
Timing has real limits, though. Results vary with load, caches, and the compiler; small inputs are dominated by noise; and it only tells you about the inputs you tried.
Counting operations
The alternative is to count, from the code, how many times each operation
runs, as a function of the input size N. For dup1 in the worst case, when
there are no duplicates:
| Operation | Count |
|---|---|
| outer loop steps | N |
values[i] == values[j] comparisons |
(N − 1) + (N − 2) + … + 1 + 0 = N(N − 1) / 2 |
| array accesses | 2 × N(N − 1) / 2 = N² − N |
For dup2, the comparisons number N − 1, and the array accesses 2N − 2.
Counting is exact and machine-independent, but tedious, and the exact counts contain detail nobody needs. What matters about N(N − 1)/2 is that it grows like N²; what matters about N − 1 is that it grows like N.
What would Swift print?
var comparisons = 0
let n = 6
for i in 0..<n {
for _ in (i + 1)..<n {
comparisons += 1
}
}
print(comparisons, n * (n - 1) / 2)Show answer and explanation
Answer15 15
Counting the inner loop’s steps directly gives 5 + 4 + 3 + 2 + 1 + 0 = 15, which is N(N − 1)/2 for N = 6: every pair of positions, once.
Four simplifications
CS61B reduces an exact count to its essence in four steps:
- Consider only the worst case. When the running time depends on the
input, analyze the input that makes the most work: for
dup1, an array with no duplicates. (Best and average cases are useful too, but must then be said explicitly.) - Pick a representative operation, the cost model, instead of counting
everything. For
dup1, the comparisons: every other operation runs a proportional number of times. - Ignore lower-order terms. N(N − 1)/2 = N²/2 − N/2, and for large N the N/2 hardly matters: at a million, it is less than a millionth of the total.
- Ignore multiplicative constants. N²/2 and N² grow the same way; the ½ depends on details like which operation we counted, and on the machine.
What is left is the order of growth: N² for dup1, N for dup2. Exactly
the doubling ratios from the timing table: 2² = 4 and 2¹ = 2.
Big Theta
The notation packages those simplifications into a definition. A function R(N) is Θ(f(N)), read “big Theta of f of N”, if there are positive constants k₁ and k₂ such that
k₁ · f(N) ≤ R(N) ≤ k₂ · f(N)
for all sufficiently large N. In words: R is eventually squeezed between two multiples of f. Examples:
| R(N) | Order of growth |
|---|---|
| N³ + 3N⁴ | Θ(N⁴) |
| 1/N + N³ | Θ(N³) |
| 1/N + 5 | Θ(1) |
| N·eᴺ + N | Θ(N·eᴺ) |
| 40 sin(N) + 4N² | Θ(N²) |
To check the first: for N ≥ 1, N³ ≤ N⁴, so 3N⁴ ≤ N³ + 3N⁴ ≤ 4N⁴. The constants k₁ = 3 and k₂ = 4 work. Big Theta says nothing about small N and nothing about constant factors, only about the shape of the growth.
So “dup1 takes Θ(N²) time in the worst case” is a precise claim: past some
size, its running time is between two fixed multiples of N².
Big O
Big O keeps only the upper half of the definition: R(N) ∈ O(f(N)) if
R(N) ≤ k₂ · f(N) for large N. It means “grows no faster than f”. Since an
upper bound need not be tight, N² ∈ O(N²), but also N² ∈ O(N³), and
dup2 ∈ O(N²) is true but unhelpful.
In everyday speech, programmers often say “O(N)” when they mean Θ(N). This course uses Θ when the bound is tight, and O when only an upper bound is known or meant, as in “every sort in the standard library is O(N log N)”. Lesson 37 adds the lower-bound counterpart, big Omega.
Put the lines in order
Put the lines in order so the program prints 10.
var n = 1024n /= 2steps += 1while n > 1 {var steps = 0print(steps)}
Show the correct program
var steps = 0
var n = 1024
while n > 1 {
n /= 2
steps += 1
}
print(steps)Lab 33: Asymptotics
Q0: What would Swift print?
What would Swift print?
var count = 0
let n = 8
for i in 0..<n {
for _ in 0..<i * i {
count += 1
}
}
print(count)Show answer and explanation
Answer140
The inner loop runs 0, 1, 4, 9, …, 49 times: the sum of squares up to 7², which is 140. In general this is about N³/3, so the function is Θ(N³).
What would Swift print?
var count = 0
var i = 1
while i < 100 {
for _ in 0..<i {
count += 1
}
i *= 2
}
print(count)Show answer and explanation
Answer127
The inner loop runs 1, 2, 4, …, 64 times, which adds up to 127. A geometric sum is dominated by its last term, so although there are two loops, the total is Θ(N) for a bound of N.
Q1: Count, then simplify
For each function, write the exact number of times work() runs as a formula
in N, then its order of growth. Check your formulas by counting.
func a(_ n: Int) { for i in 0..<n { for j in 0..<n where j < i { work() } } }
func b(_ n: Int) { for _ in 0..<n { work() }; for _ in 0..<n { work() } }
func c(_ n: Int) { for i in 0..<n { for _ in 0..<(n / 2) { work() }; if i % 2 == 0 { work() } } }
Show solution
var calls = 0
func work() { calls += 1 }
func a(_ n: Int) { for i in 0..<n { for j in 0..<n where j < i { work() } } }
func b(_ n: Int) { for _ in 0..<n { work() }; for _ in 0..<n { work() } }
func c(_ n: Int) { for i in 0..<n { for _ in 0..<(n / 2) { work() }; if i % 2 == 0 { work() } } }
for n in [4, 10, 100] {
calls = 0; a(n); assert(calls == n * (n - 1) / 2)
calls = 0; b(n); assert(calls == 2 * n)
calls = 0; c(n); assert(calls == n * (n / 2) + (n + 1) / 2)
}a: N(N − 1)/2, so Θ(N²). Thewhereclause filters, but the inner loop still examines N values ofjeach time: the loop itself is Θ(N²) even before countingwork.b: 2N, so Θ(N). Loops one after another add; only nested loops multiply.c: N·⌊N/2⌋ + ⌈N/2⌉, so Θ(N²). The extraworkon even steps is a lower-order term.
Q2: A doubling experiment
Write doublingRatios(sizes:run:), which times a function on inputs of each
size (keeping the fastest of three runs) and returns the ratios between
consecutive timings. Use it to estimate the exponent for dup1 and dup2.
Run it as an optimized build: swiftc -O lab.swift && ./lab.
Show solution
func doublingRatios(sizes: [Int], run: (Int) -> Void) -> [Double] {
let clock = ContinuousClock()
let times = sizes.map { n in
(0..<3).map { _ in clock.measure { run(n) } }.min()!
}
return zip(times, times.dropFirst()).map { $1 / $0 }
}
func dup1(_ values: [Int]) -> Bool {
for i in 0..<values.count {
for j in (i + 1)..<values.count where values[i] == values[j] {
return true
}
}
return false
}
let ratios = doublingRatios(sizes: [1_000, 2_000, 4_000]) { n in
_ = dup1(Array(0..<n))
}
assert(ratios.count == 2 && ratios.allSatisfy { $0 > 0 })
print(ratios.map { String(Int(($0 * 10).rounded())) }) // for dup1, about 40 (a ratio near 4)Dividing two Durations gives a Double. For dup1, ratios near 4 mean an
exponent of log₂ 4 = 2. The first ratios are often off, because small inputs are
dominated by fixed costs; trust the ratios at the largest sizes. In a debug build
the ratios still approach 4, but every time is several times larger.
Q3: Identify the order
Give the order of growth of each expression.
- 3N² + 1000N + 10⁹
- N log N + 100N
- 2ᴺ + N¹⁰⁰
- (N + 1)(N − 1) / N
- log(N²)
Show solution
- Θ(N²). The constant 10⁹ is huge, but constant.
- Θ(N log N). log N eventually exceeds 100, so N log N dominates 100N.
- Θ(2ᴺ). Every exponential eventually beats every polynomial, even N¹⁰⁰.
- Θ(N). It equals N − 1/N.
- Θ(log N). log(N²) = 2 log N, and constants are ignored. For the same reason, the base of a logarithm never matters in Θ.
Q4: Without sorting
dup2 needs a sorted array. Write dup3, which works on any array in Θ(N)
expected time using a Set, and give the order of growth of sorting first and
then calling dup2.
Show solution
func dup3(_ values: [Int]) -> Bool {
var seen = Set<Int>()
for value in values {
if !seen.insert(value).inserted {
return true
}
}
return false
}
func dup2(_ values: [Int]) -> Bool {
for i in 0..<max(values.count - 1, 0) where values[i] == values[i + 1] {
return true
}
return false
}
assert(dup3([5, 1, 4, 1]) && !dup3([3, 2, 1]) && !dup3([]))
assert(dup2([5, 1, 4, 1].sorted()) == dup3([5, 1, 4, 1]))Sorting takes Θ(N log N) (Lessons 54 to 56 prove that no comparison sort does
better), so sort-then-scan is Θ(N log N) overall: the sort dominates the Θ(N)
scan. The set version is Θ(N) expected, because each set insertion takes
constant time on average, which Lesson 48 explains. The guard in dup2
also fixes a crash: 0..<-1 for an empty array.
Q5: Finding the constants
Show that R(N) = 4N² + 3N + 2 is Θ(N²) by finding constants k₁, k₂, and N₀ such that k₁N² ≤ R(N) ≤ k₂N² for all N ≥ N₀. Then check your constants with a loop.
Show solution
For N ≥ 1, 3N ≤ 3N² and 2 ≤ 2N², so R(N) ≤ 4N² + 3N² + 2N² = 9N². And R(N) ≥ 4N² always. So k₁ = 4, k₂ = 9, and N₀ = 1 work.
func r(_ n: Double) -> Double { 4 * n * n + 3 * n + 2 }
for n in stride(from: 1.0, through: 10_000, by: 1) {
assert(4 * n * n <= r(n) && r(n) <= 9 * n * n)
}A loop cannot prove the bound for every N, but it catches a wrong constant quickly, which is the same role tests play for code.
Q6 (optional): Estimating the exponent
Given timings at sizes that are not powers of two, the exponent k in T(N) ≈ c·Nᵏ
can be estimated from any two points: k = log(T₂/T₁) / log(N₂/N₁). Write
estimateExponent(_:) that takes (size, seconds) pairs and returns the
estimate from the two largest sizes. Test it on synthetic data.
Show solution
import Foundation
func estimateExponent(_ samples: [(size: Double, seconds: Double)]) -> Double {
let points = samples.sorted { $0.size < $1.size }.suffix(2)
let (a, b) = (points.first!, points.last!)
return log(b.seconds / a.seconds) / log(b.size / a.size)
}
let quadratic = [1_000.0, 3_000, 9_000].map { (size: $0, seconds: 2e-9 * $0 * $0) }
let linear = [1_000.0, 5_000].map { (size: $0, seconds: 7e-8 * $0) }
assert(abs(estimateExponent(quadratic) - 2) < 0.01)
assert(abs(estimateExponent(linear) - 1) < 0.01)log comes from Foundation, which is available wherever Swift runs. The
constants 2e-9 and 7e-8 cancel in the ratio, which is exactly why the exponent
can be estimated without knowing them. Estimating from the two largest
sizes follows the advice from Q2: small inputs are dominated by fixed costs.
What’s next
Next lesson: disjoint sets, a data structure whose three versions have very different orders of growth, and the subject of Project 8.