# Q-3: Pace from distance and time, checked three ways

Data-Driven Athletics tutorial · Week 1 · Chapter 1 · about 15 min · workflow steps: Gather, Statistics

Web page: https://apopt.com/course/tutorials/q03-pace-three-ways/ · Data: https://apopt.com/data/tutorials/q03-pace-three-ways/

## The decision

A runner wants to compare this week's runs with last month's by pace. Before any comparison,
decide which time the pace uses and prove that the function computing it handles units.

## The raw data

- `raw/activities.csv`: one row per run, 19 runs from 10 April to 18 May 2026, with distance, moving and elapsed time, a pace column, heart rate and cadence The instructor's own watch runs, from the course case file `athletes/jh/watch/` (converted from the watch's FIT files; GPS positions removed), published under his name.

### A function you can trust

Pace is time per kilometer: pace = t / (d / 1000), with t in seconds and d in meters. It is one
line of code and still easy to get wrong: kilometers typed as meters, minutes as seconds, or a
pace in decimal minutes read as minutes and seconds. The habit from Section 4.1.1 is to check
a function against **three known cases** before it touches real data: one ordinary case, one
round-number case, and one that tests a unit. An `assert` line stops the notebook if a case
fails, which is what you want.

Work the three cases by hand first: 10 km in 50:00, 5 km in 22:30, and one mile (1609.344 m,
exact) in 8:00.

*Predict first:* One mile in 8:00. What is the pace per kilometer, in minutes and seconds?

```python
def speed_pace(distance_m, seconds):
    """Speed (m/s) and pace (s per km) from a distance in meters and a time in seconds."""
    if distance_m <= 0 or seconds <= 0:
        raise ValueError("distance and time must both be positive")
    v = distance_m / seconds
    return v, 1000 / v

def mmss(s):
    return f"{int(s // 60)}:{s % 60:04.1f}"

assert abs(speed_pace(10_000, 50 * 60)[1] - 300) < 1e-9          # ordinary: 5:00 /km
assert abs(speed_pace(5_000, 22 * 60 + 30)[1] - 270) < 1e-9      # round number: 4:30 /km
assert abs(speed_pace(1609.344, 8 * 60)[1] - 298.26) < 0.01      # a unit: miles to meters
try:
    speed_pace(0, 600)
    raised = False
except ValueError:
    raised = True
assert raised                                                     # an empty activity stops it
for d, t in [(10_000, 3000), (5_000, 1350), (1609.344, 480)]:
    v, p = speed_pace(d, t)
    print(f"{d:9.3f} m in {mmss(t)}: {v:.3f} m/s, pace {mmss(p)} /km")
print("all four checks pass")
```

Output:

```
10000.000 m in 50:00.0: 3.333 m/s, pace 5:00.0 /km
 5000.000 m in 22:30.0: 3.704 m/s, pace 4:30.0 /km
 1609.344 m in 8:00.0: 3.353 m/s, pace 4:58.3 /km
all four checks pass
```

The mile is the case that catches a function written for kilometers: 8:00 a mile is 4:58.3 a
kilometer, not 8:00. A distance of zero stops with a clear message instead of an infinite pace.

### Apply it to the instructor's watch

The course's case file holds 19 of the instructor's runs from spring 2026, one row each, with the
distance, the **moving time** (the watch stops counting while he stands still) and the
**elapsed time** (start to finish, stops included). Compute the pace both ways.

*Predict first:* For a run with a long stop in the middle, which pace is slower, and by roughly how much?

```python
import pandas as pd

runs = pd.read_csv("raw/activities.csv")
d_m = runs["distance_km"] * 1000
runs["pace_moving_s"] = [speed_pace(d, 60 * t)[1] for d, t in zip(d_m, runs["moving_time_min"])]
runs["pace_elapsed_s"] = [speed_pace(d, 60 * t)[1] for d, t in zip(d_m, runs["elapsed_time_min"])]
show = runs[["date", "distance_km", "moving_time_min", "elapsed_time_min"]].copy()
show["moving"] = runs["pace_moving_s"].map(mmss)
show["elapsed"] = runs["pace_elapsed_s"].map(mmss)
print(show.head(5).to_string(index=False))
assert (runs["pace_moving_s"] <= runs["pace_elapsed_s"]).all()    # stops never make you faster
print(f"elapsed pace is slower by a median of {mmss((runs['pace_elapsed_s'] - runs['pace_moving_s']).median())} per km")
```

Output:

```
      date  distance_km  moving_time_min  elapsed_time_min moving elapsed
2026-04-10       11.567            59.95             85.16 5:11.0  7:21.7
2026-04-11       14.326            69.15             80.22 4:49.6  5:36.0
2026-05-04        8.606            40.63             40.63 4:43.3  4:43.3
2026-05-04        8.674            47.74             70.52 5:30.2  8:07.8
2026-05-05        8.343            41.85            111.15 5:01.0 13:19.4
elapsed pace is slower by a median of 2:03.9 per km
```

### The third way: the file's own pace column

The file already has a column `pace_min_per_km`. Which time does it use, and in which unit?

```python
first = runs.iloc[0]
print(f"file says {first['pace_min_per_km']} min/km; moving pace {mmss(first['pace_moving_s'])}, "
      f"elapsed pace {mmss(first['pace_elapsed_s'])}")
gap = (runs["pace_min_per_km"] * 60 - runs["pace_moving_s"]).abs().max()
print(f"largest difference from the moving pace, all 19 runs: {gap:.1f} s/km")
print(f"read as 5 min 18 s by mistake, the first run would be {5 * 60 + 18 - first['pace_moving_s']:.0f} s/km too slow")
```

Output:

```
file says 5.18 min/km; moving pace 5:11.0, elapsed pace 7:21.7
largest difference from the moving pace, all 19 runs: 0.3 s/km
read as 5 min 18 s by mistake, the first run would be 7 s/km too slow
```

The column is the moving pace, in **decimal minutes**: 5.18 means 5.18 minutes, which is
5:10.8, not 5:18. Every one of the 19 runs agrees with the function's moving pace to within
0.3 s per kilometer, the rounding of the column. Reading the decimal as minutes and seconds
would make the first run 7 s per kilometer slower than it was.

### One chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 3.4))
x = range(1, len(runs) + 1)
ax.plot(x, runs["pace_moving_s"] / 60, "o", label="moving time")
ax.plot(x, runs["pace_elapsed_s"] / 60, "s", mfc="none", label="elapsed time")
ax.set(xlabel="run number (in date order)", ylabel="pace (min per km)", xticks=range(1, len(runs) + 1, 2))
ax.invert_yaxis()                      # faster at the top, as runners read pace
ax.legend()
plt.tight_layout()
print(f"slowest elapsed pace {runs['pace_elapsed_s'].max() / 60:.1f} min/km on {runs.loc[runs['pace_elapsed_s'].idxmax(), 'date']}")
```

Output:

```
slowest elapsed pace 16.3 min/km on 2026-05-16
```

![Pace in minutes per kilometer for each of the 19 runs in date order, two markers per run. The moving pace sits between about 4.6 and 6.0 minutes per kilometer; the elapsed pace is the same on non-stop runs and far slower, up to about 16 minutes per kilometer, on runs with long stops.](https://apopt.com/course/tutorials/q03-pace-three-ways/c07-1.png)

On runs with no stops the two markers sit on top of each other. On others, stops at lights,
water and conversations make the elapsed pace minutes slower. Neither is wrong; a report must
say which it used.

**For the athlete:** "On your 10 April run you averaged 5:11 a kilometer while moving; counting
the stops it was 7:22, so when we compare runs we will always use the moving pace."

## With your own data

Export one of your own runs from your watch or phone app (distance, moving and elapsed time),
add a row to the table, and check that your app's average pace matches one of your two paces.
Which one it matches tells you how your app treats pauses.

## References

- *Data-Driven Athletics*, Chapter 4, A Working Setup (Section 4.1) and its exercise extending the pace listing; Chapter 1, the case-file exercise on pace.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
