Engineering / Field note
Parser benchmarks need separate CPU and memory measures
A runnable synthetic XML comparison separates elapsed time, process CPU time and traced Python allocations, with equivalent outputs and retained trials.
A parser benchmark needs separate readings for elapsed time, process CPU time and a clearly named memory counter. A smaller number becomes useful only after the extraction result still matches. This worked comparison uses an original, generated XML fixture to make those boundaries visible. It is an engineering exercise checked on November 22, 2026, rather than a software release announcement.
Save the five Python blocks below, in order, as bench.py, then run python bench.py. The complete program generates synthetic-products.xml beside the script and prints a JSON report. It uses Python’s standard library and was validated on CPython 3.15.2 for Windows with Expat 2.9.0. Those are the tested runtime details; a different environment deserves a fresh run.
1. Declare the input
The fixture contains 20,000 invented products with identifiers, integer prices and repetitive names. It contains no scraped pages, customer records or external service calls. Fixed generation makes its byte count and SHA-256 useful replay checks. This intentionally simple shape keeps the experiment understandable; it does not reproduce every complication of a real feed.
The example reads its own generated XML. Python’s XML documentation separately discusses risks when processing untrusted input and notes that the Expat version depends on the interpreter’s configuration. Changing the input’s trust boundary requires a separate parsing-policy review. [6]
import gc, hashlib, json, platform, random
import statistics, subprocess, sys, time, tracemalloc
import xml.etree.ElementTree as ET
import pyexpat
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATA = HERE / "synthetic-products.xml"
COUNT = 20000
TRIALS = 4
def make_fixture(path, count):
with path.open("w", encoding="utf-8", newline="\n") as out:
out.write("<catalog>\n")
for number in range(count):
item = ET.Element(
"product", id=f"P{number:05d}",
cents=str(100 + number % 900),
name="Synthetic item " + "x" * 40)
out.write(ET.tostring(item, encoding="unicode") + "\n")
out.write("</catalog>\n")2. Define what counts as the same answer
Both readers must produce the same record count, total price and ordered digest of identifiers, prices and names. The digest catches differences that a row count alone would miss. Here order is part of the contract. If your application ignores order, declare and implement a different normalization rule before measuring.
The full-tree reader finishes building its ElementTree before summarizing products. Opening and parsing the local file, extracting fields and computing the digest all belong to the measured job. Network transfer, fixture generation, imports and child-process startup sit outside that interval. Naming this boundary prevents a parser comparison from quietly becoming a comparison of unrelated preparation work. [3]
def summarize(elements):
count = total_cents = 0
digest = hashlib.sha256()
for item in elements:
identifier = item.attrib["id"]
cents = int(item.attrib["cents"])
name = item.attrib["name"]
if cents < 0:
raise ValueError("negative synthetic price")
record = json.dumps(
[identifier, cents, name],
ensure_ascii=False, separators=(",", ":"))
digest.update((record + "\n").encode("utf-8"))
count += 1
total_cents += cents
return [count, total_cents, digest.hexdigest()]
def full_tree(path):
root = ET.parse(path).getroot()
return summarize(root.iter("product"))3. Release records deliberately
The second reader consumes completed product events and releases the root’s children as it goes. ElementTree documents that iterparse performs blocking reads and builds a tree incrementally; incremental parsing alone does not free that tree. Its end events provide completed elements. Our clearing strategy relies on this fixture’s flat, attribute-only product records. Nested documents need their own retention rules. [3]
def streaming(path):
with path.open("rb") as source:
events = ET.iterparse(source, events=("start", "end"))
_, root = next(events)
def completed_products():
for event, item in events:
if event == "end" and item.tag == "product":
yield item
# Valid here: products are direct children with attributes.
root.clear()
try:
return summarize(completed_products())
finally:
events.close()
CASES = {"full_tree": full_tree, "streaming": streaming}4. Separate clocks from allocation tracing
Python’s process_time measures the current process’s user and system CPU time and excludes sleep. perf_counter measures elapsed duration, including waiting. Their nanosecond variants return integer units without promising nanosecond precision; the report also records each clock’s advertised implementation and resolution. Comparing the differences between readings is the meaningful operation. [1]
Allocation trials deliberately run separately from timing trials. tracemalloc reports current and peak sizes of traced Python memory blocks, and collecting traces has overhead. We interpret that peak as a Python-allocation measurement. Whole-process resident memory is a different question, and this program does not measure it. Calling both counters simply ‘RAM’ would lose the distinction the experiment is meant to preserve. [2]
def one_trial(case, mode, path):
gc.collect()
function = CASES[case]
if mode == "clock":
wall_start = time.perf_counter_ns()
cpu_start = time.process_time_ns()
result = function(path)
cpu_ns = time.process_time_ns() - cpu_start
wall_ns = time.perf_counter_ns() - wall_start
return {"result": result, "cpu_ns": cpu_ns, "wall_ns": wall_ns}
if mode == "allocation":
tracemalloc.start()
try:
result = function(path)
current, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
return {"result": result, "traced_current_bytes": current,
"traced_peak_bytes": peak}
raise ValueError("unknown measurement mode")5. Keep the evidence, including the unexciting parts
Each recorded trial runs in a fresh child process. subprocess.run waits for completion; check=True rejects a failing child and the timeout bounds each attempt. The driver checks every returned extraction signature before retaining a row. Trial order is shuffled with a fixed seed, and all rows survive alongside the summaries. A fresh process controls interpreter state, while earlier reads can still warm the operating system’s file cache. [4]
def driver():
make_fixture(DATA, COUNT)
expected = full_tree(DATA)
if expected != streaming(DATA) or expected[0] != COUNT:
raise RuntimeError("extraction results differ")
fixture_bytes = DATA.read_bytes()
rows = []
order = [(case, mode) for case in CASES
for mode in ("clock", "allocation")]
rng = random.Random(42)
for trial in range(TRIALS):
rng.shuffle(order)
for case, mode in order:
run = subprocess.run(
[sys.executable, str(Path(__file__).resolve()),
"--worker", case, mode, str(DATA)],
capture_output=True, text=True, check=True, timeout=30)
row = json.loads(run.stdout)
if row["result"] != expected:
raise RuntimeError("worker output changed")
rows.append({"trial": trial, "case": case, "mode": mode, **row})
summaries = []
for case, mode in [(c, m) for c in CASES
for m in ("clock", "allocation")]:
selected = [r for r in rows if r["case"] == case and r["mode"] == mode]
fields = ("cpu_ns", "wall_ns") if mode == "clock" else (
"traced_peak_bytes", "traced_current_bytes")
summaries.append({"case": case, "mode": mode, **{
field: {"min": min(r[field] for r in selected),
"median": statistics.median(r[field] for r in selected),
"max": max(r[field] for r in selected)}
for field in fields}})
report = {
"python": sys.version, "implementation": platform.python_implementation(),
"system": platform.system(), "expat": pyexpat.EXPAT_VERSION,
"parser": "xml.etree.ElementTree (CPython standard library)", "fixture_records": COUNT,
"fixture_bytes": len(fixture_bytes),
"fixture_sha256": hashlib.sha256(fixture_bytes).hexdigest(),
"expected": expected, "trials_per_case_and_mode": TRIALS,
"clock_info": {name: vars(time.get_clock_info(name))
for name in ("perf_counter", "process_time")},
"rows": rows, "summaries": summaries}
print(json.dumps(report, indent=2))
if __name__ == "__main__":
if len(sys.argv) == 5 and sys.argv[1] == "--worker":
print(json.dumps(one_trial(sys.argv[2], sys.argv[3], Path(sys.argv[4]))))
elif len(sys.argv) == 1:
driver()
else:
raise SystemExit("Run without arguments, or use the documented worker form.")Four trials per reader and measurement mode produce 16 retained rows. The report includes the fixture fingerprint, Python and Expat versions, clock details and complete results. Its summaries retain minimum, median and maximum values. Python’s median uses the middle value, or the average of the middle two values for an even-sized sample. Keeping the spread makes a tidy middle number easier to question. [5]
In our retained local run, full-tree and streaming CPU medians both measured 46.875 milliseconds. Their median traced-allocation peaks were 10,658,106 and 310,085 bytes respectively. Every trial returned the same 20,000-record signature. Additional hand-authored fixtures checked Unicode, ordering and rejected inputs. These are observations about this generated workload and implementation, with four samples in each group.
Our interpretation is modest: this example demonstrates a retention difference under the named allocation counter, while these timing samples do not justify a speed claim. Before replacing a production parser, add representative permitted inputs, declare acceptable output differences, measure the relevant process-memory counter and repeat under realistic load. The useful result is a replayable explanation of what changed, backed by the records that survived the comparison.
Sources + further reading
Source dates describe the original material. Publication above is the date this Zyel article went live.
- Python 3.15: process CPU time and performance countersPython Software Foundation · Checked Nov 22, 2026
- Python 3.15: traced memory allocationsPython Software Foundation · Checked Nov 22, 2026
- Python 3.15: ElementTree parsing and incremental retentionPython Software Foundation · Checked Nov 22, 2026
- Python 3.15: subprocess.runPython Software Foundation · Checked Nov 22, 2026
- Python 3.15: median and descriptive statisticsPython Software Foundation · Checked Nov 22, 2026
- Python 3.15: XML security and ExpatPython Software Foundation · Checked Nov 22, 2026
Reader discussion
What would you ask next?
Questions, useful corrections and thoughtful disagreement are welcome. Comments are reviewed before they appear.
No reader comments yet.