Example

One Python loop against eight array rolls

Run Conway's Life twice on the same random grid, cell by cell in Python and then as eight array rolls, and assert the two outputs are identical.

A cellular automaton is local, and that does not mean it should be updated cell by cell in Python. For a dense grid the same local rule is applied everywhere, and that regularity is what array programming is good at.

This program runs both versions on the same random grid and asserts that they agree exactly: reference first, speed second, and the proof is the assertion.

Run it

Save this as vectorize.py and run it with Python 3.11 or later. It needs NumPy only.

import numpy as np
from time import perf_counter


def life_step_slow(grid):
    height, width = grid.shape
    next_grid = np.zeros_like(grid)

    for y in range(height):
        for x in range(width):
            total = 0
            for dy in (-1, 0, 1):
                for dx in (-1, 0, 1):
                    if dx == 0 and dy == 0:
                        continue
                    total += grid[(y + dy) % height, (x + dx) % width]

            alive = grid[y, x] == 1
            next_grid[y, x] = total == 3 or (alive and total == 2)

    return next_grid


def life_neighbors(grid):
    total = np.zeros_like(grid, dtype=np.int16)

    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            if dx == 0 and dy == 0:
                continue
            total += np.roll(np.roll(grid, dy, axis=0), dx, axis=1)

    return total


def life_step(grid):
    n = life_neighbors(grid)
    return ((n == 3) | ((grid == 1) & (n == 2))).astype(np.uint8)


rng = np.random.default_rng(42)
state = rng.integers(0, 2, size=(64, 64), dtype=np.uint8)

slow = life_step_slow(state)
fast = life_step(state)

assert np.array_equal(slow, fast)
print("one step identical:", bool(np.array_equal(slow, fast)))
print("live cells:", int(slow.sum()), "of", slow.size)

life_step_slow(state)
life_step(state)
t0 = perf_counter()
life_step_slow(state)
t1 = perf_counter()
life_step(state)
t2 = perf_counter()
print("vectorized step is faster:", (t2 - t1) < (t1 - t0))

The program is the chapter’s own code composed into one file: the cell-by-cell reference, the vectorized neighbor count, the vectorized rule, and the chapter’s equivalence check with its assert np.array_equal(slow, fast). The timing lines are the one addition: they time one call of each version after a warm-up and report only the comparison, so the output does not depend on machine speed.

Expected outcome

one step identical: True
live cells: 1099 of 4096
vectorized step is faster: True

The two implementations produce the same grid, cell for cell, and the vectorized one is faster here. The chapter’s own measurements put the gap at roughly 33x at 48 by 48 and about 190x at 256 by 256, widening with size, “because the loop pays per cell while the array form pays per operation”.

Where the loop went

The reference version is worth keeping even though it is slower, because it states the mechanism in one place: for each cell, add the eight neighbors, then apply the rule; the vectorized version changes only where the work is done.

def life_neighbors(grid):
    total = np.zeros_like(grid, dtype=np.int16)

    for dy in (-1, 0, 1):
        for dx in (-1, 0, 1):
            if dx == 0 and dy == 0:
                continue
            total += np.roll(np.roll(grid, dy, axis=0), dx, axis=1)

    return total

The rule then becomes boolean array logic over the grid.

One detail decides whether the two versions can be compared. np.roll reintroduces wrapped-around elements by definition, which is why every roll-based helper in this book implements periodic boundaries, and the reference loop gets the same boundary from its modulo. The chapter is blunt: “The boundary semantics come free with the function; changing them requires changing the function.” The equality assertion is only meaningful because both agree on the boundary model. The chapter’s table records the cost of the alternative: the slice variant avoids the roll temporaries but “equal only interior, boundary differs”, a different model, not a faster one.

Mechanism and limitations

Documented: the chapter states that the fast form “is the same rule Chapter 6 already runs, re-derived here as the equivalence target”; that np.roll implements periodic boundaries by construction; that optimization “should be tested against the simplest correct implementation”; and that vectorized code “can be faster while allocating more memory”.

Observed: the run above. The reference and the vectorized step produced identical 64 by 64 grids, the assertion held, and the vectorized call was faster. The reference read 36,864 cells per step, the vectorized form eight passes over the grid.

Not shown. The program compares one grid at one size, so the chapter’s scaling claim is not demonstrated: the gap is not measured at 48 by 48, at 256 by 256, or across a range of sizes, and the speedup ratio quoted above is the chapter’s number, not a measurement from this run. Only the periodic boundary is exercised, so the slice variant and the boundary difference the chapter tabulates are untested. Memory allocation is not measured. The batch axis, elementary_step and the GPU path are named in the chapter and appear in none of them.

Read the chapter .

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.