TExcelTAD
Home › Foundations of Algorithm Analysis › The RAM Model: What Counts as a Step

The RAM Model: What Counts as a Step

To say "insertion sort takes about n2/4n^2/4 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.

  1. One instruction at a time. Instructions run in sequence; there is no parallelism.
  2. 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: ==, <<, ≤\le 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.
  3. Random access. Reading or writing any memory cell costs the same, whether it is cell 0 or cell 10910^9. That is what "random access" means here: no cost for distance.
  4. Words are not arbitrarily large. For inputs of size nn, a word holds clg⁡nc \lg n bits for some constant c≥1c \ge 1.

The last assumption is the subtle one. It must be at least lg⁡n\lg n 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 lg⁡n\lg n 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 kk by the name ckc_k. Then the running time of an algorithm on an input is

T=∑kck⋅(number of times line k runs).T = \sum_{k} c_k \cdot (\text{number of times line } k \text{ runs}).

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.

text
ARRAY-SUM(a)
1  s = 0
2  for i = 0 to n - 1
3      s = s + a[i]
4  return s

Line 1 runs once. The loop test on line 2 runs n+1n + 1 times (the last test fails and ends the loop). Line 3 runs nn times and line 4 once. So

T(n)=c1+c2(n+1)+c3n+c4=(c2+c3) n+(c1+c2+c4),T(n) = c_1 + c_2 (n + 1) + c_3 n + c_4 = (c_2 + c_3)\,n + (c_1 + c_2 + c_4),

a linear function of nn whatever the constants are. The program below counts the line executions directly and confirms the pattern.

python · try it yourself
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 nn
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 nn comparisons or additions
a[i:j] copies j−ij - i elements
a.insert(0, x), a.pop(0) shifts all nn elements
sorted(a) about nlg⁡nn \lg n 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.

python · try it yourself
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 nn 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 x=2x = 2 and square it kk times: the result is 22k2^{2^k}, whose length doubles with every squaring.

python · try it yourself
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 2642^{64} to 0 instead of growing:

cpp · try it yourself
#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 bb bits occupies about b/(clg⁡n)b / (c \lg n) 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 2k2^k is not a primitive instruction in general, but for small kk it is a single left shift of the bit pattern 1, so most analyses treat "2k2^k for kk 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 clg⁡nc \lg n bits?

  1. So that a word can hold array indices, while one instruction cannot process arbitrarily large numbers
  2. Because real computers have exactly lg⁡n\lg n bits per word
  3. To make addition slower than multiplication
  4. So that the memory has exactly nn cells

In ARRAY-SUM, how many times does the loop test on line 2 run for an array of nn elements?

  1. n−1n - 1
  2. nn
  3. n+1n + 1
  4. 2n2n

Which Python operation on a list of length nn is a constant number of RAM steps?

  1. x in a
  2. a.pop(0)
  3. a[i] = x
  4. a[2:n]

Which of these does the basic RAM model take into account?

  1. Cache misses
  2. The number of primitive instructions executed
  3. Several cores running at once
  4. The exact clock speed of the processor