#python #programming #computerscience #performance
I recently started a course on Advanced Computer Architecture.
While reading Computer Architecture: A Quantitative Approach by David A. Patterson and John L. Hennessy, I came across a concept that made me rethink how I write everyday software: data-level parallelism.
I've been writing software since undergrad, and like most developers, I care about clean code, sensible abstractions, and algorithmic complexity. What I hadn't fully connected was how the CPU actually executes the code I write.
Modern processors have several features that help them run software efficiently:
- SIMD instructions process multiple values with one instruction.
- CPU caches keep frequently accessed data close to the processor.
- Branch prediction helps the CPU anticipate which instructions come next.
- Multiple cores allow independent tasks to run in parallel. The way we structure our data and loops can make it easier or harder for software to use these capabilities.
One caveat before we start: in Python, the biggest performance effect by far is usually avoiding the interpreter, not any single hardware feature. I'll point out where that matters as we go, because it changes what each example actually proves.
1. SIMD: Doing more with one instruction
SIMD stands for Single Instruction, Multiple Data. A scalar operation handles one pair of values at a time. With SIMD, the processor uses wider registers to hold several values and performs the same operation on all of them together.
On x86, for example:
; Scalar: one single-precision float movss xmm0, [rdi] addss xmm0, [rsi] ; SIMD (SSE): four single-precision floats movups xmm0, [rdi] movups xmm1, [rsi] addps xmm0, xmm1 The ss instructions operate on one scalar value, while the ps instructions operate on packed values. Here, a 128-bit SSE register holds four 32-bit floats. Modern CPUs also support wider extensions: AVX2 handles 8 floats per instruction and AVX-512 handles 16.
The key idea: the CPU can perform the same operation on several values at once.
So how does this show up in everyday Python?
2. Python loops vs. contiguous arrays
Imagine an API endpoint receives one million transaction amounts and needs to add 15% tax plus a $0.30 processing fee to each one.
import timeit import statistics import numpy as np prices = [float(i % 100) + 0.99 for i in range(1_000_000)] prices_array = np.array(prices) # float64, same precision as Python floats def python_loop(): return [p * 1.15 + 0.30 for p in prices] def numpy_version(): return prices_array * 1.15 + 0.30 for name, fn in [("Python", python_loop), ("NumPy", numpy_version)]: times = timeit.repeat(fn, number=1, repeat=7) print(f"{name}: {statistics.median(times):.5f}s (median of 7)") Note what this does: both versions use 64-bit floats, so they do equivalent numeric work, and we report the median of several runs instead of a single timing.
On typical hardware, NumPy wins by a large margin, often 10x to 100x. But why?
Most of that gap is interpreter overhead, not SIMD. In CPython, every loop iteration involves bytecode dispatch, type checks, reference counting, and allocating a new float object, which costs tens of nanoseconds per element. A Python list also stores references to float objects scattered around the heap rather than the values themselves.
NumPy stores values in one contiguous block of memory and runs a compiled loop over it. That eliminates the per-element Python overhead, and it gives the compiled code the chance to use SIMD instructions. SIMD is a real contributor, but a smaller one here: arr * 1.15 + 0.30 makes two passes over memory and allocates a temporary array, so for large inputs it's often limited by memory bandwidth rather than compute.
One more honesty point: this benchmark assumes your data is already in a NumPy array. Converting a list with np.array(prices) takes real time, so if your data starts as a Python list and you only do one cheap operation, the end-to-end win is much smaller.
3. Conditional logic and branch prediction
Modern CPUs predict which way a branch will go so they can keep the instruction pipeline full. If the prediction is wrong, the work done speculatively is discarded and the pipeline restarts. That is a branch misprediction, and it costs on the order of 10 to 20 cycles.
Consider this condition:
if price > 50: discount = price * 0.90 else: discount = price * 0.98 Applied to a million prices in pure Python:
discounted = [p * 0.90 if p > 50 else p * 0.98 for p in prices] And vectorized with NumPy:
rates = np.where(prices_array > 50, 0.90, 0.98) discounted = prices_array * rates np.where is a good idiom: it expresses the conditional across the whole array and runs it in compiled code. But I want to be careful about what this example demonstrates. It is not a branch-prediction demo. In the Python loop, interpreter overhead dwarfs any misprediction cost, and my sample data (i % 100 + 0.99) is a regular repeating pattern that a predictor handles easily anyway.
Branch misprediction really shows up in compiled code on unpredictable data. The classic experiment is a C loop that sums values above a threshold, run once over random data and once over the same data sorted:
for (size_t i = 0; i < n; i++) { if (data[i] >= 128) sum += data[i]; } Sorted data makes the branch predictable and the loop runs much faster; random data makes the branch unpredictable and the loop slows down noticeably (compilers may turn the branch into a conditional move or vectorize it, so check your optimization level). That's the effect to look for with a tool like perf stat, which reports branch-misses.
4. Lists of dictionaries vs. separate arrays
Application developers commonly represent records as lists of dictionaries:
users = [ {"id": i, "active": True, "score": float(i % 100)} for i in range(500_000) ] That's perfectly reasonable. But what if we only need the average score?
# Access scores through dictionaries avg_dict = sum(u["score"] for u in users) / len(users) # Extract into a NumPy array, then average (end-to-end) scores = np.array([u["score"] for u in users]) avg_array = scores.mean() If you time these two end-to-end, don't be surprised if NumPy is not faster, or even slower. Building the array requires the same walk over every dictionary, so you pay the dictionary cost plus the conversion cost. The benefit only appears when the data already lives in a columnar layout:
# Data stored by column from the start scores = np.array([float(i % 100) for i in range(500_000)]) avg = scores.mean() # this is the part that's fast So what makes the dictionary version slow? Several things add up: hashing the key on every lookup, chasing pointers to dict objects and boxed floats scattered across the heap, and interpreter overhead. Cache behavior is part of it, since the CPU fetches memory in blocks called cache lines (typically 64 bytes), and a contiguous array uses every byte of each line it loads. But it's one factor among several, not the whole story.
This connects to two common data layouts:
- Array of Structures (AoS): each record stores its fields together.
- Structure of Arrays (SoA): each field has its own separate array. Neither is universally better. If you frequently access every field of a record, grouping fields together makes sense. If you process one field across hundreds of thousands of records, separate columns are usually more efficient. This is exactly why columnar tools like pandas, Arrow, and Parquet are fast for analytics. Choose the layout based on how the data will be accessed.
A note on benchmarking
Actual speedups depend on your processor, Python version, NumPy build, data types, and input size. To get meaningful numbers:
- Run each benchmark multiple times and compare medians.
- Make sure both implementations do equivalent work (same data types, same output).
- Include data preparation and conversion if it would happen in real use.
- To actually isolate hardware effects like cache misses and branch mispredictions, compare compiled code and use hardware counters (
perf staton Linux), because in Python the interpreter noise hides them. The goal isn't to promise that NumPy is always a certain number of times faster. It's to understand why performance differences exist and when they matter.
Final thoughts: Good hardware needs good software
Studying computer architecture hasn't made me want to rewrite every backend in C. Readable, maintainable code still matters.
But it has changed how I think about performance. A computer can have plenty of RAM, a fast processor, and many cores and still run poorly structured software slowly. A program might access memory in ways that make poor use of the caches, do unnecessary work, or have unpredictable branches that disrupt the pipeline. It might also run tasks sequentially when parts of the workload could run in parallel across cores.
In Python specifically, the first lesson is usually to get the hot loop out of the interpreter and into compiled, vectorized code. The deeper lessons about memory layout, caches, branches, and SIMD then determine how much more you can get once you're there.
My biggest takeaway is that efficient software isn't only about choosing better algorithms or buying more powerful hardware. It's also about writing code that lets the hardware do what it was designed to do.
And that's one of the things I'm enjoying most about studying computer architecture: understanding what's happening beneath the code I've been writing for years.
