Activity 35: Where does the boundary go?
Name:
You're shipping the sensor scoring program from today's lecture. Here it is, one box per piece.
You'll sort these twice, for two different callers.
The pieces
┌───────────────────────────────────────────┐
│ [1] │
│ struct Reading { │
│ id: u32, │
│ value: f64, │
│ baseline: f64, │
│ } │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [2] │
│ fn load_readings(path: &str) │
│ -> Vec<Reading> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [3] │
│ fn parse_line(line: &str) │
│ -> Option<Reading> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [4] │
│ fn score_one(r: &Reading) -> f64 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [5] │
│ fn score_all(rs: &[Reading]) -> Vec<f64> │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [6] │
│ fn adjust(x: f64) -> f64 │
│ // caps a score at 100.0 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [7] │
│ fn mean(xs: &[f64]) -> f64 │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [8] │
│ fn summary(rs: &[Reading]) -> Summary │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [9] │
│ const DRIFT_THRESHOLD: f64 = 0.05; │
└───────────────────────────────────────────┘
┌───────────────────────────────────────────┐
│ [10] │
│ fn is_drifting(r: &Reading) -> bool │
└───────────────────────────────────────────┘
Part 1: a Rust caller (in lecture)
You're publishing this as a library crate. Somebody else's Rust project will add it to their Cargo.toml.
Sort all ten boxes into two piles, by number.
Public. You write pub on it, and you're promising to keep it:
Private. You can rename or delete it tomorrow:
People will disagree about one of these ten. Which one, and what's the argument on each side? Compare with a neighbor if you like.
Answer. Public: Reading (a caller needs the type to use anything else), load_readings, score_all, mean, summary, is_drifting.
Private: parse_line, adjust, and DRIFT_THRESHOLD. They're helpers for the main functions and we might want to change them later without breaking what gets used publically.
score_one is the contraversial one. Public is defensible: scoring a single reading is a reasonable thing to want, and it's hard to justify keepign score_one private if score_all is private. Private is defensible too, because publishing it invites callers to write their own loop over it, and we might later want to change internals around score_all.
Part 2: now a Python caller
Same code. Different person on the other side.
Your teammate has a pandas DataFrame with a value column and a baseline column, a million rows each, and a for loop over them that's the slowest step in their pipeline.
Re-sort the boxes. Which ones cross into Python?
Crosses:
Stays in Rust:
score_all can't cross in its current shape. Why not, and what would you change its signature to?
Answer. The set of public functions gets smaller.
load_readings and parse_line stay private. Pandas already loaded the file, and read_csv is compiled code underneat. mean stays too. NumPy has its own, and it's fast enough.
Reading doesn't cross, but then Python has no Reading. So score_all can't keep &[Reading]. It becomes:
fn score_all(values: Vec<f64>, baselines: Vec<f64>) -> Vec<f64>
summary and is_drifting could cross if you reshape them the same way
Part 3: two designs, same job
Two people on your team expose the scoring to Python in different ways.
Design A calls into Rust once per row.
import sensor_scoring
scores = []
for row in df.itertuples():
scores.append(sensor_scoring.score_one(row.value, row.baseline)) # 1,000,000 calls
Design B hands both columns over once.
import sensor_scoring
scores = sensor_scoring.score_all(df["value"].tolist(), df["baseline"].tolist()) # 1 call
Both produce the same numbers, and the Rust arithmetic inside is identical.
1. Predict: which is faster, and why?
2. One of these can end up slower than the plain Python loop it replaced. Which one, and how is that possible?
Answer. Design B. On a million readings we measured a plain Python loop at about 100 ms, Design A at about 115 ms, and Design B at about 28 ms.
Every trip across the boundary converts Python objects into Rust types, and back again on the way out. B pays that once, A pays it a million times.
Design A is the one that loses to plain Python. The conversion costs more than the subtraction it's wrapped around, so A added work to every row.
The rule: cross the boundary rarely, and carry a lot each time.
Part 4: back to week two (if there's time)
In week two we added up ten million numbers in Python and again in Rust, and Rust was around 350x faster.
Now you know how to use both in one program. Suppose that program also had to load its numbers from a CSV and plot the result.
Which pieces would you write in Rust, and which would you leave in Python?
Answer. Loading and plotting stay in Python. The ten-million-number loop goes to Rust, handed over in one call.