The RAM Model: What Counts as a Step
To say "insertion sort takes about steps on average" you first have to agree on what a step is. Real computers have caches, pipelines, branch predictors and several cores, and the same program can run twice as fast on Tuesday's laptop as on Monday's. Analysis needs something simpler and more stable: an idealised machine whose costs are easy to count and still predict real behaviour well. The standard choice is the random-access machine, or RAM model.
The machine
Picture a single processor attached to a large memory of numbered cells, called words. The model makes a handful of assumptions.
- One instruction at a time. Instructions run in sequence; there is no parallelism.
- Primitive instructions take constant time. Each of these costs one unit (or some fixed constant):
- arithmetic on words: add, subtract, multiply, divide with remainder, floor and ceiling;
- comparisons: , , and so on;
- data movement: load a word from memory, store a word, copy a word;
- control: a conditional or unconditional jump, calling a procedure and returning from it.
- Random access. Reading or writing any memory cell costs the same, whether it is cell 0 or cell . That is what "random access" means here: no cost for distance.
- Words are not arbitrarily large. For inputs of size , a word holds bits for some constant .
The last assumption is the subtle one. It must be at least bits, otherwise a word could not even hold the index of the last array element. But if words could be arbitrarily large, one "multiply" could do an enormous amount of work in a single step, and the model would stop resembling any real computer. A constant multiple of bits is the compromise: indices and counters fit, unbounded numbers do not.
Pseudocode lines as steps
With the RAM model fixed, every pseudocode line that involves no procedure call and no hidden loop does a constant amount of work. Call the constant for line by the name . Then the running time of an algorithm on an input is
The constants depend on the machine and are not known, but they do not need to be: the counts carry the information about how the cost grows. The Counting Steps Exactly lesson does this for insertion sort in full. Here is a smaller case: summing an array.
ARRAY-SUM(a)
1 s = 0
2 for i = 0 to n - 1
3 s = s + a[i]
4 return sLine 1 runs once. The loop test on line 2 runs times (the last test fails and ends the loop). Line 3 runs times and line 4 once. So
a linear function of whatever the constants are. The program below counts the line executions directly and confirms the pattern.
from collections import Counter
def array_sum(a, runs):
runs[1] += 1; s = 0
i = 0
while True:
runs[2] += 1 # the loop test
if i > len(a) - 1:
break
runs[3] += 1; s = s + a[i]
i += 1
runs[4] += 1
return s
for n in [0, 1, 5, 100]:
runs = Counter()
array_sum(list(range(n)), runs)
print(f"n = {n:>3}: line 1: {runs[1]}, line 2: {runs[2]:>3}, line 3: {runs[3]:>3}, line 4: {runs[4]}")n = 0: line 1: 1, line 2: 1, line 3: 0, line 4: 1
n = 1: line 1: 1, line 2: 2, line 3: 1, line 4: 1
n = 5: line 1: 1, line 2: 6, line 3: 5, line 4: 1
n = 100: line 1: 1, line 2: 101, line 3: 100, line 4: 1
Python lines are not always one step
A single line of Python can hide a whole loop. When you analyse Python code, you have to look through these lines to the work they do.
| Python | RAM cost on a list of length |
|---|---|
a[i], a[i] = x, len(a), a.append(x) |
constant (append is constant on average, see amortized analysis later in the track) |
x in a, a.index(x), a.count(x), min(a), sum(a) |
up to comparisons or additions |
a[i:j] |
copies elements |
a.insert(0, x), a.pop(0) |
shifts all elements |
sorted(a) |
about comparisons |
You can watch a hidden loop at work by counting comparisons. The class below wraps a number and counts every == test made on it; Python's in operator then reveals how many elements it inspects.
class Counted:
tests = 0
def __init__(self, v):
self.v = v
def __eq__(self, other):
Counted.tests += 1
return self.v == other.v
a = [Counted(v) for v in range(1000)]
for target in [0, 499, 999, 5000]:
Counted.tests = 0
found = Counted(target) in a
print(f"{target:>4} in a -> {found!s:<5} equality tests: {Counted.tests}") 0 in a -> True equality tests: 1
499 in a -> True equality tests: 500
999 in a -> True equality tests: 1000
5000 in a -> False equality tests: 1000
One line, x in a, costs anywhere from 1 to steps depending on the input. Treating it as one step would make a quadratic algorithm look linear.
Why the word size matters
Python integers grow without limit, which is convenient but outside the RAM model. Repeated squaring shows why the model forbids it. Start from and square it times: the result is , whose length doubles with every squaring.
x = 2
for k in range(1, 8):
x = x * x
print(f"after {k} squarings: {x.bit_length():>3} bits")
x = 2
for k in range(30):
x = x * x
print(f"after 30 squarings: {x.bit_length():,} bits")after 1 squarings: 3 bits
after 2 squarings: 5 bits
after 3 squarings: 9 bits
after 4 squarings: 17 bits
after 5 squarings: 33 bits
after 6 squarings: 65 bits
after 7 squarings: 129 bits
after 30 squarings: 1,073,741,825 bits
In C++
A C++ std::uint64_t is exactly one fixed-size word, the RAM model's assumption made concrete. The sixth squaring would need 65 bits, so the result wraps around modulo to 0 instead of growing:
#include <bit>
#include <cstdint>
#include <cstdio>
int main() {
// a C++ integer is one fixed-size word: 64 bits here
std::uint64_t x = 2;
for (int k = 1; k <= 7; k++) {
x = x * x; // unsigned arithmetic wraps around modulo 2^64
std::printf("after %d squarings: %2d bits, x = %llu\n",
k, (int)std::bit_width(x), (unsigned long long)x);
}
}after 1 squarings: 3 bits, x = 4
after 2 squarings: 5 bits, x = 16
after 3 squarings: 9 bits, x = 256
after 4 squarings: 17 bits, x = 65536
after 5 squarings: 33 bits, x = 4294967296
after 6 squarings: 0 bits, x = 0
after 7 squarings: 0 bits, x = 0
Thirty "steps" built a number of about a billion bits, 128 megabytes of memory. If every multiplication counted as one step regardless of size, an algorithm could compute such numbers "in constant time", which no machine can do. Under the word-size rule, a number of bits occupies about words and arithmetic on it costs accordingly. Algorithms that genuinely work with huge numbers, such as RSA, are analysed by counting bit operations instead.
Gray areas and what the model ignores
Some operations sit on the boundary. Computing is not a primitive instruction in general, but for small it is a single left shift of the bit pattern 1, so most analyses treat " for less than the word size" as constant time. The model also deliberately ignores:
- the memory hierarchy: real reads from cache are far faster than reads from main memory, and those are far faster than disk. External-memory models (used for B-trees later in the track) count block transfers instead;
- parallelism: multi-core and vector instructions. The Selected Topics course introduces a model for them;
- constant factors: a step on one machine may be three times a step on another.
None of this makes the RAM model useless. It answers the question it is designed for: how does the cost of an algorithm grow with its input? For that, it is remarkably accurate.
Test yourself
Why does the RAM model limit a word to bits?
- So that a word can hold array indices, while one instruction cannot process arbitrarily large numbers
- Because real computers have exactly bits per word
- To make addition slower than multiplication
- So that the memory has exactly cells
In ARRAY-SUM, how many times does the loop test on line 2 run for an array of elements?
Which Python operation on a list of length is a constant number of RAM steps?
x in aa.pop(0)a[i] = xa[2:n]
Which of these does the basic RAM model take into account?
- Cache misses
- The number of primitive instructions executed
- Several cores running at once
- The exact clock speed of the processor