Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Predicting the speedup

Comparing builds measures what psync did. psync-predict tells you what it would do, before you annotate anything, from one run of the code as it is. You give it the function and a trace of that run: the source line of each call, and how long it took. It replays psync’s schedule over those costs.

cargo run -p psync-graph --features cli --bin psync-predict -- src/profile.rs 3 run.trace

An example

Take profile_page from the introduction, and one measured run of it, in milliseconds:

#[psync::graph]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> {
    let user = api.user(user_id).await?;
    let posts = api.posts(user_id).await?;
    let avatar = api.avatar(&user.avatar_url).await?;
    let friends = api.friends(user_id).await?;
    Ok(Page { user, posts, avatar, friends })
}
# one sequential run, in ms: LINE COST
3 40
4 120
5 60
6 80
profile_page: 300 as measured, 120 predicted with psync
speedup: 2.50x
  region: 300 -> 120
    level 0: 120, set by n1 (line 4)

psync runs user then avatar (100 ms) next to posts (120 ms) and friends (80 ms). The level takes as long as its slowest chain, posts on line 4: that is the critical path. Making user or avatar faster would not help. Making posts faster would, down to 100 ms.

How the prediction works

The trace is of the code as written, so the calls in it are the ones that run took: a call on a branch that was not taken has no line in the trace. The prediction is for that path. To cover several paths, give several runs (below).

  • A region costs, per level, its slowest chain, where a chain costs the sum of its calls. Levels run one after another.
  • A prefetched loop first runs the prefix of every item, at most bound at once, each starting as soon as a slot frees. The rest of each body then runs in order.
  • Everything else, such as calls before a lock or outside any region, costs what it cost.

This is psync’s schedule, not an ideal one. A level waits for all of its chains (Levels), and the prediction does too.

Checked against measurement

tests/predict.rs checks every prediction against the rewritten function’s measured time. Each test function has two copies, one #[graph(off)] and one #[graph]. A traced timer records the line it is called from. The sequential copy’s trace predicts the other copy’s time, and the test measures it:

FunctionSequentialPredictedMeasured
a tree of four calls (one waits for two)704040
two chains whose edges cross806060
a guarded call, branch taken704040
the same, branch not taken302020
a loop of 6 items, bound = 3963333
the same loop, bound = 16963131

The same file checks profile too. A #[graph(profile)] copy of each function reports exactly the trace the timer recorded, so its trace predicts the same time.

Time there is counted in executor rounds, and a simulated call is ready a fixed number of rounds after it starts, as a timer would be. (An earlier version of the test counted each call’s own polls. That made calls in a bounded join look faster than they are, because the join polls some futures more than once per round.)

Several runs: a critical path per path

A function with a branch has more than one critical path. Here the avatar comes from a cache, and only a miss asks the API:

#[psync::graph]
async fn profile_page(api: &Api, cache: &Cache, user_id: u64) -> Result<Page, Error> {
    let user = api.user(user_id).await?;
    let posts = api.posts(user_id).await?;
    let mut avatar = cache.get_avatar(&user.avatar_url).await;
    if avatar.is_none() {
        let fetched = api.avatar(&user.avatar_url).await?;
        avatar = Some(fetched);
    }
    let friends = api.friends(user_id).await?;
    Ok(Page { user, posts, avatar, friends })
}

Put several runs in one trace, separated by ---. Two hits and a miss:

# three runs of the function as written, in ms: LINE COST
3 40
4 120
5 2
10 80
---
3 40
4 120
5 2
7 60
10 80
---
3 45
4 110
5 2
10 85

psync-predict groups the runs by the lines they ran, which is the path they took, and predicts each path:

profile_page: 3 runs, 2 path(s); mean 262.0 as measured, 138.7 predicted with psync
path 0: 2 of 3 runs (67%), lines [3, 4, 5, 10]: 242.0 -> 117.0 (2.07x)
  its slowest run (run 0): 242 -> 122
    region: 242 -> 122
      level 0: 120, set by n1 (line 4)
      level 1: 2, set by n2 (line 5)
path 1: 1 of 3 runs (33%), lines [3, 4, 5, 7, 10]: 302.0 -> 182.0 (1.66x)
  its slowest run (run 1): 302 -> 182
    region: 302 -> 182
      level 0: 120, set by n1 (line 4)
      level 1: 2, set by n2 (line 5)
      level 2: 60, set by n3 (line 6)

Each path is a condition (here: the cache missed, line 7 ran) with its own critical path, and the share of runs that took it says how much that critical path matters. On a hit, posts (line 4) sets the time. On a miss, the avatar request adds a level of its own, 60 ms after everything in level 0, although it only needs user. That is psync’s schedule: the if waits for the cache read, which waits for user, and user has two later statements depending on it, so they are not fused into one chain with it, and each starts a new level (Chain fusion). The what-if says what fixing it is worth: overlapping the miss with posts would take path 1 from 182 to about 120 ms (the chain user, cache, miss is 102 ms, under posts’ 120), on a third of the runs. Levels with no measured time (a branch not taken, a generated statement) are not printed.

A path is told apart only by a statement that awaits inside the branch and is timed on its own line. A match whose arm awaits (None => api.avatar(..).await?) is one statement, timed once, so its hits and misses look like one path with two costs. Each group’s mean is then a mixture.

Getting a trace

Add profile to the attribute, install a clock and a sink, and run the program once:

#[psync::graph(profile)]
async fn profile_page(api: &Api, user_id: u64) -> Result<Page, Error> { /* as before */ }

fn main() {
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    psync::profile::install(
        || START.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64,
        |line, cost| eprintln!("{line} {cost}"),
    );
    // ... run the program
}

profile compiles the function as written, like off. Every statement that awaits reports its line and how long it took to the sink, which here prints one trace line to stderr, in microseconds. A statement that awaits inside a nested block, such as the if of a guarded call, is timed once, by the innermost statement. Async blocks and closures inside the function are separate futures and are not timed. With no clock installed, profile reports nothing, so psync needs no std for it.

Any other timing source works too, as long as it gives the line of each statement and its cost in one unit. Spans inside a callee (#[instrument] on posts) record the callee’s line, though, which is not what the prediction needs.

On the graph suite

graph_suite runs every example a third time, profiled, and prints the prediction next to the measured rewrite, in its predicted column. Its timers are real, so this checks the prediction against wall-clock time. All 16 predictions are within 0.3 ms of the measured rewrite, for runs of 8 to 191 ms.

Getting there took three fixes, each found by a miss:

  • A sample can sit inside its node. In matrix-rust-sdk, the node is an if let on line 75 and the profiled call is on line 76. Matching by first line found no node, so the prediction counted that call as sequential (90 ms predicted, 60 ms measured). Nodes now carry their last line too, and a sample belongs to the node whose lines contain it.
  • A prefix may start without awaiting. In delta-rs, the prefix is a format! and then a request. Only the request is profiled, so splitting items at the prefix’s first line found none. Items now start wherever the prefix starts again.
  • An inner loop runs once per outer item. In neon, the five downloads of each shard were pooled into one bounded run of twenty, which predicted 171 ms against 191 ms. A sample outside the loop now ends a run of it.

A fourth miss was in psync’s report itself. In quickwit, a guarded call hoisted into a loop’s prefix was reported on the guard’s line only, so its time could not be found. The node now spans the statements it took.

Limits

  • A statement left by ?, return or break reports nothing under profile. Trace a run without an early exit, or expect the prediction to miss that statement’s time.
  • A statement in a region is matched by the lines it spans. Within a prefetched loop, items are told apart by where the prefix starts again, so a prefix must await before the rest of the body does.
  • The prediction counts waiting only. With everything arriving at once, CPU work after the waits can become the bottleneck (Patterns and pitfalls), and servers may slow down under the extra load.

Prior work and novelty

WorkWhat it doesHow psync differs
Critical path analysis (Yang and Miller, ICDCS 1988)The longest weighted path in the program activity graph decides the run time.psync’s per-path critical path is this analysis, on the graph of the proposed schedule, grouped by control path with the share of runs that took each path.
Coz (Curtsinger and Berger, SOSP 2015)Measures what would happen if a line were faster, by slowing everything else.Coz runs an experiment per line. psync predicts one kind of change, overlapping waits, from traces and the static graph, without running it.
WebProphet (Li et al., NSDI 2010)Predicts how a page’s load time changes when its fetches change, from a dependency graph inferred by perturbing timings.The closest precursor. psync’s graph comes from the code, not from perturbation, and the change it predicts is an automatic rewrite.
Kremlin (PLDI 2011)Reportedly predicts the speedup of parallelizing regions of C programs.Not read yet. Until it is, psync does not claim its predictor is new.

Exercises

  1. In the profile_page trace, avatar takes 90 ms instead of 60. What does psync-predict print for the level, and which line sets it?
  2. A loop of 8 items has a prefix of one request of 40 ms, and a body after it of 5 ms per item. Predict its time with bound = 4 and with bound = 16.
  3. You trace a run in which fetch()? fails on its first item and the function returns early. What is wrong with predicting from that trace?
  4. In the cache example, the miss rate rises to 90% (nine misses and one hit, same costs). What is the mean predicted time? Which line is worth making faster first?
Answers
  1. user then avatar is now 40 + 90 = 130 ms, more than posts (120 ms): level 0: 130, set by n0 (line 3) -> n2 (line 5), and 130 predicted against 330 measured. Speeding up posts no longer helps at all.
  2. With bound = 4, the prefixes run in two rounds of four: 80 ms, then the bodies in order, 8 × 5 = 40 ms: 120 ms, against 8 × 45 = 360 ms sequentially. With bound = 16, all eight prefixes run at once: 40 + 40 = 80 ms.
  3. The trace has the path the run took: one request and an exit, not the loop. The ? also left its statement before profile reported it, so even that request’s time is missing. Trace a run that takes the path you want predicted.
  4. 0.9 × 182 + 0.1 × 122 = 176 ms, against 0.9 × 302 + 0.1 × 242 = 296 ms measured. On the common path now, the miss’s level (60 ms, line 7) comes after the 120 ms level, so both add up: posts (line 4) and the avatar request (line 7) are both on the critical path, and shortening either one helps. Removing the extra level (overlapping the miss with posts) would save the 60 ms outright.