Module 07 · Lesson 7.1
Measuring Before Optimising
On this page
- What you will learn
- Why you measure before you optimise
- Median, p95 and baseline in plain words
- Worked scenario: the slow "My orders" page
- How to record a repeatable baseline
- Step-by-step workflow
- Using an AI assistant before you have measured
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A friend says your car feels slow. You could change the tyres, the oil and the spark plugs and hope for the best. Or you could drive a measured mile, write down the time, and then change one thing. The second way is slower to start and much faster to finish.
Slow software works the same way. In this lesson you will turn "the page feels slow" into a clear symptom, a target and a baseline you can repeat. The example continues the fictional Tidewell Wholesale service tidewell-orders. Trade customers say their "My orders" page is slow. All people, accounts and numbers are invented.
What you will learn
- Write a symptom statement that names the action, the account, the numbers and the target.
- Explain median and p95 in plain words, and say why an average can hide a problem.
- Record a baseline with a method that someone else can repeat.
- Decline to optimise until the cost is located, even when an assistant offers a quick fix.
Before you start
- You finished Modules 1 to 5, ending with Writing a Reviewable Pull Request. Module 6, Dependency Upgrades and Migrations, is not needed first.
- You can run a short Python script. Python 3.11 or newer is fine.
- A system you may measure, such as a staging copy. Do not test against production without permission.
Why you measure before you optimise
Optimising means making something faster or lighter. It sounds like a pure good. It is not free. Every change can add bugs, make code harder to read, or fix something that was never the problem.
People are bad at guessing where time goes. Think of a restaurant where customers wait too long. Most people would blame the cook. Often the wait is at the till, or in the queue to be seated. You find out only by timing each step.
A measurement does three jobs. It tells you how bad the problem is. It points to where to look. And later, it proves whether your change helped. Without a starting number, "it feels faster" is only an opinion.
Median, p95 and baseline in plain words
One request is never enough. Times change from run to run, like the time of your drive to work. So you send many requests and look at the pattern. These words describe the pattern.
- Median
- The middle value when you sort all the times. Half the requests were faster and half were slower. It shows what a typical visit feels like. Think of the middle person in a queue sorted by height.
- p95 (95th percentile)
- The time that 95 out of 100 requests beat. Only 1 in 20 was slower. It shows how bad the slow visits are. If your trip to work usually takes 20 minutes but one day in twenty takes 50, the 50 is your p95.
- Mean (average)
- All the times added up and divided by the count. One very slow request pulls the mean up, and many fast ones pull it down. So the mean can look fine while some users suffer.
- Baseline
- The measurement you take before you change anything. It is your 'before' photo. You compare every later measurement with it.
- Warm-up request
- A first request that you send and then throw away. The first one often pays extra costs, such as opening connections or filling caches. Think of a kettle: the first cup takes longer because the kettle is cold.
- Target
- The number that means 'good enough', agreed before you start. For example: p95 under 0.5 seconds. Without a target, you never know when to stop.
Why p95 and not only the median? Users remember the slow visits. A page that is fast most of the time but crawls one time in twenty feels broken. That is why teams often set targets on p95.
Worked scenario: the slow "My orders" page
A support engineer passes on a complaint. Trade customers with long order histories say the portal's "My orders" page is slow. You know the path from Mapping Entry Points and Data Flow: GET /api/orders/ is handled by OrderListView in api/views.py. It calls order_history(customer_id, limit=50) in orders/selectors.py. That function returns the latest 50 orders with their lines, product names and totals.
You do not start by reading code for ideas. You first write the symptom down as a statement that anyone could check.
| Part of the statement | Tidewell example |
|---|---|
| Action | Open "My orders": GET /api/orders/ |
| Who or what | Account TC7-0042, with about 1,800 orders |
| Where | The staging copy of the service, at a quiet time |
| Method | 30 requests after one warm-up request |
| Result | Median 2.4 s, p95 4.1 s |
| Comparison | Small accounts (under 50 orders): about 0.2 s |
| Target | p95 under 0.5 s for any account |
Read the comparison row again. Small accounts are fast and the big account is slow. That already tells you something: the cost grows with the number of orders. It does not tell you why. That comes in the next lessons.
How to record a repeatable baseline
A baseline is only useful if you can take the same measurement again after your change. That means the method must be written down. Here is a simple way to collect the timings with curl, a command-line tool that sends web requests.
URL="https://staging.example.com/api/orders/"
# 31 requests: the first is the warm-up and is dropped by tail.
for i in $(seq 1 31); do
curl -s -o /dev/null -w "%{time_total}\n" \
-H "Authorization: Bearer $PORTAL_TOKEN" "$URL"
done | tail -n +2 > baseline_before.txt
wc -l < baseline_before.txtSend 31 requests and keep the last 30 times. Set PORTAL_TOKEN to a test account's token first; never paste a real token into notes.
What each part does
curl -s -o /dev/nullsends the request and hides the page body, so only the timing is left.-w "%{time_total}\n"prints how many seconds the whole request took.seq 1 31repeats the request 31 times.tail -n +2drops the first line, which is the warm-up.- The last line prints how many timings were saved. You expect 30.
Now the maths. Python's standard library has a statistics module. The functions below work out the median, the mean and the p95 from a list of times. They also show how to run a baseline with an injected clock, so you can test the code without waiting.
import math
import statistics
WARMUP = 1
RUNS = 30
def p95(durations):
"""Nearest-rank p95: the value that 95% of the runs were at or below."""
ordered = sorted(durations)
rank = math.ceil(0.95 * len(ordered))
return ordered[rank - 1]
def summarise(durations):
return {
"runs": len(durations),
"median": statistics.median(durations),
"mean": statistics.mean(durations),
"p95": p95(durations),
"slowest": max(durations),
}
def run_baseline(call, clock, warmup=WARMUP, runs=RUNS):
for _ in range(warmup):
call() # the warm-up request is thrown away
durations = []
for _ in range(runs):
start = clock()
call()
durations.append(round(clock() - start, 3))
return durationsA small measuring kit. p95 uses the 'nearest rank' rule: sort the times and take the 29th of 30.
What each part does
p95sorts the times, then picks the value at rank 95% of the way along. With 30 runs that is the 29th value.summarisereturns the numbers you will write in your note: runs, median, mean, p95 and the slowest.run_baselinecalls the thing you are measuring. It throws away the warm-up calls, then times each real call with the clock it is given.- Passing
clockin as a parameter is what makes the function testable. A test can give it a fake clock.
To see it work without a staging server, the script below replays 30 fixed timings through a fake clock. They stand in for the team's staging log. The numbers are written into the script so you get the same answer every time. They are made up to match the story.
from measure import run_baseline, summarise
# Stand-in for the 30 staging timings (seconds), in the order they arrived.
STAGING_SECONDS = [
2.4, 3.2, 2.1, 2.5, 2.3, 4.6, 2.2, 2.7, 2.0, 2.4,
3.6, 2.3, 2.9, 2.4, 2.2, 4.1, 2.1, 2.5, 3.0, 2.3,
2.0, 2.8, 2.4, 3.4, 1.9, 2.2, 3.8, 2.3, 4.0, 2.6,
]
def fake_clock_for(durations):
"""A clock that replays start and end times, so the demo never varies."""
stamps, now = [], 0.0
for d in durations:
stamps += [now, now + d]
now += d + 1.0
ticks = iter(stamps)
return lambda: next(ticks)
def call_endpoint():
pass # the real version sends GET /api/orders/ for account TC7-0042
durations = run_baseline(call_endpoint, fake_clock_for(STAGING_SECONDS))
result = summarise(durations)
print("Endpoint: GET /api/orders/ account: TC7-0042")
print(f"runs: {result['runs']} (after 1 warm-up)")
print(f"median: {result['median']:.2f} s")
print(f"mean: {result['mean']:.2f} s")
print(f"p95: {result['p95']:.2f} s")
print(f"slowest: {result['slowest']:.2f} s")
print("target p95 under 0.50 s:", "met" if result["p95"] < 0.5 else "NOT met")Replays 30 fixed timings and prints the baseline.
Endpoint: GET /api/orders/ account: TC7-0042
runs: 30 (after 1 warm-up)
median: 2.40 s
mean: 2.71 s
p95: 4.10 s
slowest: 4.60 s
target p95 under 0.50 s: NOT metLook at the three numbers. The median is 2.40 s and the mean is 2.71 s. They are close, but the p95 is 4.10 s. One visit in twenty takes almost twice as long as a typical one. A report that gave only the mean would hide that.
Write the method next to the numbers
Numbers without a method cannot be repeated. Keep a short note beside them. It is the part most people skip, and the part you will thank yourself for later.
# My orders: baseline (before any change)
- Date: 2026-11-19. Commit: the hash of the commit deployed to staging.
- Request: GET /api/orders/ as account TC7-0042 (about 1,800 orders).
- Method: 1 warm-up request, then 30 requests, one at a time, from the
same machine, using baseline.sh. Quiet time, no other tests running.
- Result: median 2.4 s, mean 2.7 s, p95 4.1 s, slowest 4.6 s.
- Comparison: accounts under 50 orders take about 0.2 s.
- Target: p95 under 0.5 s for any account.
- Not measured: production load, other endpoints, cold caches.A baseline note. Commit it with the change so the 'before' is never lost.
Step-by-step workflow
Step 1: Capture the complaint in the user's words
Write down who said it, which page or action, and when. 'Slow' is a feeling. Ask for an example account, if you can have one, and a rough time.
What you should see: A one-line complaint with a source and an example.
Step 2: Turn it into a symptom statement
Name the action, the account, the environment, the numbers you will take and a comparison case. Write the target now, before you see results.
What you should see: A statement in the table format above.
Step 3: Fix the conditions
Choose the environment, the data and the quiet time. Note the commit. Close other work that could disturb the numbers.
What you should see: Conditions another person could set up again.
Step 4: Take the baseline
Send one warm-up request, then at least 30 timed requests. Compute the median and the p95. Keep the raw list too.
What you should see: A baseline note with raw timings and a summary.
Step 5: Check the baseline is stable
Run it a second time. If the median moves a lot, something else is changing, such as a busy server. Find out what before you trust it.
What you should see: Two runs that agree, or a noted reason why not.
Step 6: Only then look for the cost
Move on to profiling and reading evidence. Do not edit code yet. A fix before the evidence is a guess.
What you should see: Permission to start the next lesson, with a baseline in hand.
- Complaint
In the user's words
- Symptom statement
Action, account, target
- Fixed conditions
Environment, data, commit
- Baseline
1 warm-up, 30 runs
- Stable?
Run twice
- Look for the cost
Next lesson
The target is written before the results, so you cannot move the goalposts afterwards.
Using an AI assistant before you have measured
Imagine you paste the endpoint's code into an assistant and ask "how do I make this faster?". It will answer with confidence. Often it says "add caching" or "use a faster library". These are common answers to a common question. They are not answers about your system.
Caching stores a result so the next request can reuse it. It can help a lot. It also adds the risk of showing old data, and a customer's order list that is five minutes out of date is a new bug. If the real cost is somewhere else, the cache does nothing useful.
- Use it to: sharpen your symptom statement, suggest what to measure, and draft the baseline note.
- Give it: the symptom statement, your method and the numbers. Leave out real customer data.
- Ask it for: the questions you should answer before changing code, and what could make your baseline unreliable.
- Do not accept: a fix offered before there is evidence. Ask 'what would we measure to know if that helps?'.
Conclusion and your next step
You now have a symptom statement, a target and a baseline for the slow "My orders" page. You know why the median, the p95 and a written method matter, and why a fix without a measurement is a guess.
Your next step: find where the time goes. Continue with Profiling and Reading the Evidence and count the queries behind that one page.
For more, read Load Testing with AI: Generating Realistic Performance Test Scenarios and the module overview Performance and Reliability Investigation.
Reusable prompt
Symptom statement and baseline plan
Helps you turn a vague performance complaint into a symptom statement, a target and a baseline plan, before any code is changed.
I am investigating a performance complaint in a Python and Django service called tidewell-orders (fictional). I have NOT changed any code and I do not want a fix yet.
Complaint (from a support engineer): trade customers with long order histories say the "My orders" page is slow.
Endpoint: GET /api/orders/ (OrderListView). It returns the latest 50 orders with lines, product names and totals.
What I know: account TC7-0042 has about 1,800 orders. Small accounts (under 50 orders) take about 0.2 s. I plan to measure on staging.
Please give me:
1. A symptom statement with these parts: action, account, environment, method, comparison and a proposed target (suggest one and say why).
2. A baseline plan: how many warm-up and timed requests, which statistics to record (median and p95), and what to write in the note so someone else can repeat it.
3. A list of things that could make my baseline unreliable (for example noisy neighbours, caches, different data).
4. The questions I should answer BEFORE changing any code.
Do not propose optimisations. If you are unsure, say so. Mark any guess as (unverified).Show the reusable template
Replace each {{placeholder}} with your own details.
I am investigating a performance complaint in {{system_description}}. I have NOT changed any code and I do not want a fix yet.
Complaint: {{complaint_in_users_words}}
Endpoint or action: {{endpoint_and_what_it_returns}}
What I know: {{known_facts_and_comparison}}. I plan to measure on {{environment}}.
Please give me:
1. A symptom statement with these parts: action, account, environment, method, comparison and a proposed target (suggest one and say why).
2. A baseline plan: how many warm-up and timed requests, which statistics to record (median and p95), and what to write in the note so someone else can repeat it.
3. A list of things that could make my baseline unreliable (for example noisy neighbours, caches, different data).
4. The questions I should answer BEFORE changing any code.
Do not propose optimisations. If you are unsure, say so. Mark any guess as (unverified).Expected output and limitations
A short symptom statement, a baseline plan and two lists: risks to the measurement and questions to answer first. It should not contain a fix. If it proposes caching or an index, the prompt was not followed.
Symptom statement
- Action: GET /api/orders/ (My orders)
- Account: TC7-0042, about 1,800 orders
- Environment: staging, quiet time
- Method: 1 warm-up, then 30 timed requests, one at a time
- Comparison: accounts under 50 orders take about 0.2 s
- Proposed target: p95 under 0.5 s (proposed; confirm with the product owner)
Baseline plan
- Record median, p95, slowest and the raw list of timings.
- Write the commit, environment, account and time of day in the note.
Could make the baseline unreliable
- Other tests or deploys running on staging
- Staging data that differs from production
- Caches filled by earlier requests
Answer before changing code
- Is the time spent in the database, in Python, or waiting on something else?
- Does the time grow with the number of orders? Measure a 10-order and a 500-order account.
- (unverified) Is the slow part the query or the response size?Limitations to keep in mind
- The assistant has not seen your system. Its target is a suggestion; the target is a decision for people.
- It may add a fix anyway. Delete it, and keep the questions.
- It cannot know whether staging looks like production. You have to check that.
- It cannot run the baseline. Only your measurements count.
Common errors and how to fix them
Reporting only the average
Why it happens: The average is the easiest number to compute, so it is the one that gets quoted.
Fix: Always record the median and the p95, and keep the raw list. One slow outlier can hide inside a fine-looking mean.
Measuring once, or on a cold system
Why it happens: One request is quick to take, and the first request often pays extra start-up costs.
Fix: Send a warm-up request and throw it away. Then take at least 30 timed requests and run the whole thing twice.
Changing code before writing the target
Why it happens: The fix feels obvious, and the goal is only in someone's head.
Fix: Write the target in the symptom statement first. Otherwise 'faster' can mean anything, and you cannot tell when you are done.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Write a baseline for one slow path in your repository
Pick one slow or sluggish action in a repository or sample application you may test. Write a symptom statement and record a baseline with a written method.
You will need
- A repository or sample application you are allowed to run, and a safe environment to measure.
- The measuring kit from this lesson, or the equivalent timing tool for your language.
- A target agreed with whoever owns the feature, or a reasoned proposal.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- If you cannot find a slow page, pick the slowest test in your suite and measure that.
- If your two runs disagree by a lot, look for something else using the machine.
- If you ask an assistant for help, give it the statement and ask for questions, not fixes.
Show a model answer
A strong answer reads like the baseline note in this lesson. It names the action and the data, gives the commit, the method and the numbers, and says what was not measured. The target is written before the results. Two runs are compared and the difference is explained. A weak answer says 'the page took about 3 seconds', has no method, and moves straight to a fix.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The p95 is the time that 95% of requests beat, so around 1 in 20 is slower. It is not the average. It is also not the slowest time, which can be higher still.
Show the answer and explanation
Answer: B. Start-up costs such as opening connections can make the first request slower than the rest. Keeping it would mix a one-off cost into your numbers. The count of requests is not the reason, and servers do not need a warning.
Show the answer and explanation
Answer: B. Without a measurement you may cache something that was never slow, and add stale data for no gain. Sounding sure is not evidence. A rewrite is an even bigger change with the same problem.
Frequently asked questions
What is the difference between median and p95?
The median is the middle time: half the requests were faster and half were slower. The p95 is the time that 95 out of 100 requests beat, so it shows how bad the slow visits are. Teams look at both because a page can be quick on average and still slow for some users.
How many requests do I need for a baseline?
Thirty is a sensible start for a simple check, plus one warm-up request. More runs give steadier numbers, and fewer can be misleading. Run the whole baseline twice. If the two runs agree, you can trust it more.
Can I measure in production?
Only with permission, and carefully. Sending many test requests to a live system can slow down real customers. Staging is safer. Production monitoring that already exists, such as request timings in logs, is a good source of real numbers.
Is optimising early always wrong?
No. Choosing a sensible design is good. The warning is against changing working code for speed before you know what is slow. Measure first, then spend your effort where the numbers point.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- statistics — Mathematical statistics functions(opens in a new tab)
Python Software Foundation · Official documentation · The standard-library module used for the median and the mean.
- Monitoring Distributed Systems(opens in a new tab)
Google · Explains why percentiles describe user experience better than averages.
- Requests: Advanced Usage(opens in a new tab)
Requests project · A Python library for sending web requests, with notes on timing.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.