Percentiles
The plan talks to the course server of the sixth lesson; its whole file is repeated here, so that this page runs on its own.
server.py
#!/usr/bin/env python3 """The target server of the JMeter course: a small JSON API on 127.0.0.1. python3 server.py 8099 Every endpoint is a few lines: the course tests them, it does not test the server. /slow sleeps, /fail answers 500, /login sets a cookie and returns a token, /secure wants that token in an Authorization header. """ import json import sys import time import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse USERS = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}, {"id": 3, "name": "Linus"}] TOKEN = "secret-token" class Handler(BaseHTTPRequestHandler): """One request, one small JSON answer.""" protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): """Keep the course\\'s server log quiet: every request would be a line.""" def reply(self, status, body, ctype="application/json", headers=None): """Send a body with its length, so a keep-alive client can read it.""" data = body.encode("utf-8") self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) for name, value in (headers or {}).items(): self.send_header(name, value) self.end_headers() self.wfile.write(data) def reply_json(self, status, value, headers=None): self.reply(status, json.dumps(value), headers=headers) def do_GET(self): url = urlparse(self.path) query = parse_qs(url.query) if url.path == "/": self.reply(200, "<!doctype html><title>course</title><h1>JMeter course</h1>", "text/html") elif url.path == "/health": self.reply_json(200, {"status": "ok"}) elif url.path == "/api/users": self.reply_json(200, {"users": USERS, "count": len(USERS)}) elif url.path.startswith("/api/users/"): user = next((u for u in USERS if str(u["id"]) == url.path.rsplit("/", 1)[-1]), None) self.reply_json(200 if user else 404, user or {"error": "no such user"}) elif url.path == "/items": page = int(query.get("page", ["1"])[0]) self.reply_json(200, {"page": page, "items": [f"item-{page}-{n}" for n in range(1, 4)]}) elif url.path == "/slow": ms = int(query.get("ms", ["300"])[0]) time.sleep(ms / 1000.0) self.reply_json(200, {"slept_ms": ms}) elif url.path == "/fail": self.reply_json(500, {"error": "the server was told to fail"}) elif url.path == "/login": self.reply_json(200, {"token": TOKEN}, headers={"Set-Cookie": "session=abc123; Path=/"}) elif url.path == "/secure": if self.headers.get("Authorization") == "Bearer " + TOKEN: self.reply_json(200, {"message": "welcome"}) else: self.reply_json(401, {"error": "a token is required"}) elif url.path == "/token": self.reply_json(200, {"token": uuid.uuid4().hex}) elif url.path == "/redirect": self.reply(302, "", headers={"Location": "/health"}) elif url.path == "/xml": self.reply(200, "<user><id>1</id><name>Ada</name></user>", "application/xml") elif url.path == "/echo": body = json.dumps({"method": "GET", "path": self.path, "headers": dict(self.headers)}) self.reply(200, body) else: self.reply_json(404, {"error": "not found", "path": url.path}) def do_POST(self): length = int(self.headers.get("Content-Length", "0")) raw = self.rfile.read(length).decode("utf-8") if length else "" if self.path == "/api/orders": try: order = json.loads(raw) if raw else {} except json.JSONDecodeError: self.reply_json(400, {"error": "the body is not JSON"}) return self.reply_json(201, {"id": 1001, "received": order}) else: self.reply_json(404, {"error": "not found", "path": self.path}) if __name__ == "__main__": port = int(sys.argv[1]) if len(sys.argv) > 1 else 8099 server = ThreadingHTTPServer(("127.0.0.1", port), Handler) print(f"listening on 127.0.0.1:{port}", flush=True) server.serve_forever()
python3 server.py 8099 &
The average of a run is the number nobody experiences. One slow answer among a hundred moves it by a little and is exactly what the user of that answer remembers. A percentile names the slow answers: the 99th percentile is the value under which 99 of a hundred samples fall, so one in a hundred is worse.
Percentiles from the file
The second column of a .jtl is the elapsed time of a sample. Sort the column, take the value at the nearest rank, and the percentile is there: no library and no statistics package.
percentiles.py
"""The percentiles of a .jtl, by nearest rank. python3 percentiles.py results.jtl """ import sys rows = [line.split(",") for line in open(sys.argv[1], encoding="utf-8").read().splitlines()[1:]] values = sorted(int(row[1]) for row in rows if row) def rank(percent): """The value at the nearest rank: the first sample at or above the share.""" return values[max(0, -(-percent * len(values) // 100) - 1)] print(f"samples: {len(values)}") print(f"mean: {sum(values) / len(values):.1f} ms") for percent in (50, 90, 95, 99): print(f"p{percent}: {rank(percent)} ms") print(f"max: {values[-1]} ms")
A file whose answer is known
A file of ten samples with the elapsed times 10, 20, ... 100 milliseconds has percentiles that can be written down before the script runs: the 50th is 50, the 90th is 90 and the 99th is 100. The file is not from a run; it is the check of the script, and the page says so.
latencies.jtl
timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect
1,10,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,10,0,1
2,20,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,20,0,1
3,30,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,30,0,1
4,40,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,40,0,1
5,50,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,50,0,1
6,60,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,60,0,1
7,70,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,70,0,1
8,80,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,80,0,1
9,90,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,90,0,1
10,100,health,200,OK,Thread Group 1-1,text,true,,105,80,1,1,http://127.0.0.1:8099/health,100,0,1
python3 percentiles.py latencies.jtl
samples: 10
mean: 55.0 ms
p50: 50 ms
p90: 90 ms
p95: 100 ms
p99: 100 ms
max: 100 ms
The mean is 55 and the 99th percentile is 100: the average sits in the middle and the slow end is twice it. The dashboard prints the same numbers for a real run as pct1 (the 90th), pct2 (the 95th) and pct3 (the 99th).
The same script on a run
Twenty requests to the health endpoint give a file of twenty rows. The script reads it, and the page shows the one line of its output that does not change: the count. The milliseconds of a run are different on every machine, and the lesson prints them for a reader who runs it, not as a claim.
plan.jmx
<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Twenty samples" enabled="true">
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments">
<elementProp name="host" elementType="Argument">
<stringProp name="Argument.name">host</stringProp>
<stringProp name="Argument.value">127.0.0.1</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
</elementProp>
<elementProp name="port" elementType="Argument">
<stringProp name="Argument.name">port</stringProp>
<stringProp name="Argument.value">8099</stringProp>
<stringProp name="Argument.metadata">=</stringProp>
</elementProp>
</collectionProp>
</elementProp>
</TestPlan>
<hashTree>
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">20</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"/>
<stringProp name="ThreadGroup.delay"/>
</ThreadGroup>
<hashTree>
<ConfigTestElement guiclass="HttpDefaultsGui" testclass="ConfigTestElement" testname="HTTP Request Defaults" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.domain">${host}</stringProp>
<stringProp name="HTTPSampler.port">${port}</stringProp>
<stringProp name="HTTPSampler.protocol">http</stringProp>
<stringProp name="HTTPSampler.contentEncoding"/>
<stringProp name="HTTPSampler.path"/>
</ConfigTestElement>
<hashTree/>
<ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="results.jtl" enabled="true">
<boolProp name="ResultCollector.error_logging">false</boolProp>
<objProp>
<name>saveConfig</name>
<value class="SampleSaveConfiguration">
<time>true</time>
<latency>true</latency>
<timestamp>true</timestamp>
<success>true</success>
<label>true</label>
<code>true</code>
<message>true</message>
<threadName>true</threadName>
<dataType>true</dataType>
<encoding>false</encoding>
<assertions>true</assertions>
<subresults>false</subresults>
<responseData>false</responseData>
<samplerData>false</samplerData>
<xml>false</xml>
<fieldNames>true</fieldNames>
<responseHeaders>false</responseHeaders>
<requestHeaders>false</requestHeaders>
<responseDataOnError>false</responseDataOnError>
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
<assertionsResultsToSave>0</assertionsResultsToSave>
<bytes>true</bytes>
<sentBytes>true</sentBytes>
<url>true</url>
<threadCounts>true</threadCounts>
<idleTime>true</idleTime>
<connectTime>true</connectTime>
</value>
</objProp>
<stringProp name="filename">results.jtl</stringProp>
</ResultCollector>
<hashTree/>
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="health" enabled="true">
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
<collectionProp name="Arguments.arguments"/>
</elementProp>
<stringProp name="HTTPSampler.domain">${host}</stringProp>
<stringProp name="HTTPSampler.port">${port}</stringProp>
<stringProp name="HTTPSampler.protocol">http</stringProp>
<stringProp name="HTTPSampler.contentEncoding"/>
<stringProp name="HTTPSampler.path">/health</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<stringProp name="HTTPSampler.connect_timeout"/>
<stringProp name="HTTPSampler.response_timeout"/>
</HTTPSamplerProxy>
<hashTree/>
</hashTree>
</hashTree>
</hashTree>
</jmeterTestPlan>
jmeter -n -t plan.jmx -l results.jtl -j jmeter.log
Creating summariser <summary>
Created the tree successfully using plan.jmx
Starting standalone test @ 2026 Nov 25 15:21:40 GMT (1795620100683)
Waiting for possible Shutdown/StopTestNow/HeapDump/ThreadDump message on port 4445
summary = 20 in 00:00:01 = 17.2/s Avg: 43 Min: 42 Max: 51 Err: 0 (0.00%)
Tidying up ... @ 2026 Nov 25 15:21:42 GMT (1795620102035)
... end of run
python3 percentiles.py results.jtl | head -1
samples: 20
On a local server the 99th percentile of twenty fast calls is close to the average, because nothing in the run is slow. The lesson of the synthetic file is the one to keep: the tail of a distribution is where a plan finds its bugs, and a threshold on the 95th or 99th percentile is the number a pipeline should watch, as the next lesson does.
Related
- The HTML dashboard: the percentiles of a whole run, per label.
- The vocabulary: the words a report is made of.
- Performance testing: what a latency budget is for.
Автор статьи: Arthur Isaev