Benchmarking OSM parsing tools#

TL;DR

As of October 2026, pyrosm is the fastest and most memory-efficient tool in this benchmark for reading buildings and road networks from PBF files, on every area from the Helsinki region up to all of Spain (1.5 GB). On all of Finland, for example, it reads the buildings in under 10 s, against 41.5 s for QuackOSM and 100 s for osmextract, on a laptop with 24 GB of RAM. pyrosm also crops large .osm.pbf files about as fast as the C++-based osmium-tool: 15.9 s against 16.7 s on one thread, and 4.4 s against 3.7 s on eight threads in its fast mode, with about a tenth of osmium-tool’s peak memory.

pyrosm is a Python library for reading OpenStreetMap data from PBF files into GeoPandas GeoDataFrames. PBF (Protocolbuffer Binary Format) is the compressed binary format in which OpenStreetMap distributes its data. Most of pyrosm is written in Cython and C. It has two engines: the in-memory engine parses the whole file into memory, and the out-of-core engine reads the file in one streaming pass, keeps intermediate data on disk and decodes the data blocks on several threads at once. This keeps its peak memory low and lets it read files larger than the computer’s memory.

Here, we compare pyrosm with six other widely used OpenStreetMap tools on the same tasks:

Tool

What it is

Reads a local .osm.pbf?

pyrosm

Cython OSM→GeoPandas reader (in-memory + out-of-core engines)

yes

OSMnx

OSM→GeoPandas/NetworkX via the Overpass API

no (downloads from Overpass)

QuackOSM

DuckDB-based OSM→GeoParquet/GeoPandas reader

yes

pyosmium

Python bindings to libosmium (streaming C++ reader/writer)

yes

osmium-tool

C++ command-line tool (libosmium); filter + export to GeoJSON, read with GeoPandas

yes

Osmosis

Java command-line tool for manipulating PBF data

yes

osmextract

R package: downloads and reads OSM via GDAL into sf

yes

We benchmark three tasks:

  1. Parse buildings into a GeoDataFrame on areas from a single neighbourhood up to a whole country, measuring time and peak memory.

  2. Parse the road network (highway=* ways) in the same way.

  3. Crop a large PBF (all of Finland) down to the Helsinki region and write the result to a new .osm.pbf file.

How the comparison is kept fair#

  • Same input. Every local-file tool reads the same PBF file; OSMnx downloads the same area from the Overpass API.

  • Same selection. Each tool is given the same OSM tag filter (building / highway).

  • Same output. Tools disagree on whether a tag filter should also return tagged nodes (e.g. highway=bus_stop), so we count only polygons for buildings and lines for roads, and show the counts side by side.

  • Isolated runs. Each parse and each crop runs in its own process, and run_monitored.py records its time and peak memory. Each read is repeated several times and we report the median; for pyrosm’s road networks and its geometry-and-key buildings, the fastest of the medians of three runs on one day. Caches are cleared before every read, so each one really parses the file, and the notebook pauses after every run so that the heat of one run does not slow down the next.

  • Checked crops. Each cropped file is read back and its buildings counted, so a crop that lost data would show up.

Not every tool can do every task. OSMnx downloads from the Overpass API and cannot read or crop local files, so it is not in the cropping task. Osmosis does not build GeoDataFrames, so it only crops. osmextract (R) reads but does not crop; its results come from the companion osmextract_benchmark_scaling.ipynb notebook. osmium-tool parses by exporting GeoJSON, which GeoPandas then reads. pydriosm has no tag filter at read time, so it cannot do a like-for-like extraction and is left out.

Cores differ by tool. The parsing runs use each tool’s defaults, so some tools run on one core and others on several. pyrosm’s in-memory engine and pyosmium’s Python loop run on one core, while QuackOSM, osmium-tool and pyrosm’s out-of-core engine use several. With workers="auto", pyrosm reads files under about 20 MB on one thread, files of about 20 to 70 MB, such as the Helsinki region extract (65 MB), on up to 4 threads, and larger files on the number of CPU cores minus two (8 threads on this laptop).

Hardware#

The benchmarks were run on a MacBook Air (M5) with 24 GB of RAM, 10 CPU cores and an SSD, running macOS Tahoe 26.6.

Data#

  • Buildings are parsed across a ladder of areas of increasing size:

    • Kamppi neighbourhood (clipped from the Helsinki extract),

    • Helsinki Region (~65 MB, BBBike),

    • New York City (~153 MB, BBBike),

    • Paris (~243 MB, BBBike),

    • Finland (~771 MB, Geofabrik), and

    • Spain (~1,491 MB, Geofabrik).

    • South America (~4,139 MB, Geofabrik), used only in the head-to-head test of pyrosm and QuackOSM.

The in-memory engine is run up to Finland and skipped on Spain, where it would exceed the available memory. OSMnx is run on Kamppi and the Helsinki region only. Cropping uses all of Finland (approx. 770 MB from Geofabrik) as the large input that gets cropped down to the Helsinki region.

Results#

This section sums up the main results; the sections further below give every number and the code behind it. All runs were made on one laptop with nothing else running, so read the rankings as indicative rather than exact.

The tools return nearly the same features. From the Helsinki region up, the counts of building polygons and road lines agree across the tools to within 2 % (about 187,000 buildings and 305,000 road lines in the Helsinki region).

Parsing buildings#

From the Helsinki region up, pyrosm’s out-of-core engine is the fastest reader of buildings and uses the least memory. It reads New York City and Paris in 4.5–5.3 s, where QuackOSM takes 22–24 s and osmextract 26–28 s. On Finland it takes under 10 s (QuackOSM 41.5 s, osmextract 100 s), and on Spain 24 s (66 s and 181 s). QuackOSM with tag columns and osmium-tool need far more memory as the files grow: QuackOSM runs out of memory on Spain, and osmium-tool on Finland. On the smallest area, Kamppi, osmextract and pyosmium finish first.

pyrosm’s in-memory engine is as fast as the out-of-core engine on the small areas, but slower on the large ones (Finland 40.5 s against 9.8 s), and it needs much more memory (17.4 GB on Finland against 5.1 GB). Compared with pyrosm 0.20.0, the out-of-core engine now reads buildings nearly three times as fast (Finland 9.8 s instead of 29 s).

Buildings speed

Buildings peak memory

Parsing the road network#

Road networks show the same picture. From the Helsinki region up, pyrosm’s out-of-core engine is again the fastest and uses the least memory. It reads New York City and Paris in about 3 s and Finland in 8.3 s, where osmextract takes 7–8 s and 35 s. On Spain it takes 22 s, against 101 s for QuackOSM and 121 s for osmextract. OSMnx could not download the road networks from the public Overpass API during this benchmark (see Task 1).

Road network speed

Road network peak memory

pyrosm vs QuackOSM on the same workload#

In the charts above each tool uses its own defaults, which do not return the same tag columns. Here pyrosm and QuackOSM do exactly the same work: both read only the geometry and the building tag, on every area from Kamppi up to all of South America (4.1 GB). pyrosm is faster at every size: 4.6 to 7.5 times as fast from the Helsinki region to Finland (Finland 9.0 s against 41.7 s), nearly three times as fast on Spain (22.9 s against 66.1 s) and more than four times as fast on South America (78 s against 342 s). It also uses less memory, for example 6.7 GB against 19.8 GB on Spain.

pyrosm vs QuackOSM, matched workload

Cropping a country down to a region#

pyrosm and osmium-tool are by far the fastest croppers. On one thread, pyrosm crops all of Finland down to the Helsinki region in 15.9 s, slightly faster than osmium-tool (16.7 s). On eight threads, pyrosm’s fast mode takes 4.4 s, close to osmium-tool’s 3.7 s. The fast mode skips re-packing the data, so its file is larger (85 MB instead of 61 MB); the compact mode takes 6.4 s on eight threads. pyrosm needs less than 0.5 GB of memory in every mode, against about 4 GB for osmium-tool. Osmosis takes 189 s and pyosmium about 230 s. Compared with pyrosm 0.21.0, the eight-thread fast crop now takes less than half the time (11.7 s before), and compared with pyrosm 0.23.0 the eight-thread compact crop takes 6.4 s instead of 11.6 s.

Cropping benchmarks

Where pyrosm fits#

From the Helsinki region up to Spain, pyrosm reads buildings and road networks faster than the other tools tested, with the lowest peak memory. Only on the smallest extract (Kamppi) do osmextract and pyosmium finish first. In cropping, pyrosm is slightly faster than osmium-tool on one thread and close to it on eight, with a tenth of the memory. And it does all of this from one Python object: OSM(fp) reads buildings, roads, POIs and other layers into GeoDataFrames in one line of code (e.g. OSM(fp).get_buildings()), exports networks to igraph, NetworkX or Pandarm, and crops the file to a new PBF.

Running the tests#

The rest of this page documents how the benchmarks were run. We have tried to make the comparison as fair as possible, but we are not experts in all of these tools, and some of them may run faster with other settings. If you see a way to make the comparison fairer, please open an issue on GitHub.

Installation#

The Python tools, osmium-tool, the Java runtime for Osmosis and the notebook’s plotting and data-frame packages are installed into one environment from ci/benchmarks.yaml, which pins the versions benchmarked here; Osmosis and osmextract are then installed as shown below. pyrosm is installed from its PyPI wheel, and all of its results were measured with pyrosm 0.25.0, on 25 October 2026. The other tools were measured earlier in October 2026, with the versions pinned in the file. OSMnx, QuackOSM, pyosmium and osmium-tool come from conda-forge; Osmosis (a Java tool) and osmextract (an R package) are installed separately.

mamba env create -f ci/benchmarks.yaml
mamba activate pyrosm-benchmarks

# Osmosis 0.49.2: download it from https://github.com/openstreetmap/osmosis/releases and put
# the `osmosis` launcher on your PATH (the environment brings the Java runtime).

# osmextract (run by the companion osmextract_benchmark_scaling.ipynb) from CRAN, and the
# Jupyter kernel for R:
R -e 'remotes::install_version("osmextract", version = "0.6.0", repos = "https://cloud.r-project.org")'
R -e 'IRkernel::installspec()'

Running#

Run the notebooks from a copy of the docs/benchmarks folder outside any synced folder (such as OneDrive or Dropbox): the downloaded data, the tools’ temporary files and caches, and the results are written into that folder (data/, tmp/, the result CSV files and figures/). After every run the notebook pauses for half as long as the run took (at least 2 seconds, at most 5 minutes), so that the heat of one run does not slow down the next. Every run is logged to benchmark.log in that folder, with its start and end, its time and memory so far every 30 seconds, and the pause after it. Follow the runs in a terminal with tail -f benchmark.log.

cp -R docs/benchmarks ~/pyrosm-benchmarks
cd ~/pyrosm-benchmarks
rm osm_parsing_results.csv osmcrop_results.csv osmextract_scaling_results.csv   # the published results
caffeinate -i jupyter lab   # caffeinate keeps the Mac awake during the long runs

Run benchmarks_scaling.ipynb first, then osmextract_benchmark_scaling.ipynb (R), and then benchmarks_scaling.ipynb once more, either in JupyterLab or from a terminal with jupyter nbconvert --to notebook --execute --inplace --ExecutePreprocessor.timeout=-1 <notebook>. Each result is written to osm_parsing_results.csv (the crops to osmcrop_results.csv, and osmextract’s results to osmextract_scaling_results.csv) as soon as it is measured, and a run that finds a result already there prints it instead of measuring it again. The second run of benchmarks_scaling.ipynb therefore repeats no measurements: after two short setup steps (clipping Kamppi and reading the Helsinki region’s extent for OSMnx) it draws the tables and charts, now with osmextract’s results. A run that was stopped continues where it left off. To measure a tool again, delete its rows from the results file; the copy above starts without the published results, so that every result is measured.

If a tool is missing, its cells below are skipped automatically (they are guarded by an availability check), so the rest of the notebook still runs end to end.

Setup: imports, tool detection and helpers#

Many code cells are hidden from the website to make the report easier to read, but you can open them to see how the benchmarks are run.

Hide code cell source

import os
import time
import shutil
import statistics
import subprocess
import tempfile
import warnings
from collections import namedtuple
from pathlib import Path

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

warnings.filterwarnings("ignore")  # keep the benchmark output readable

# The data, and the temporary files and caches of this kernel and of the worker processes
# (TMPDIR), are kept in subfolders of the notebook's folder, which should not be synced.
HERE = Path.cwd()
if ("CloudStorage" in HERE.parts or "Mobile Documents" in HERE.parts
        or any(part.startswith(("OneDrive", "Dropbox")) for part in HERE.parts)):
    print("NOTE: this notebook runs inside a synced folder; copy docs/benchmarks to a local "
          "folder and run it there.")
DATA_DIR = HERE / "data"
TMP_DIR = HERE / "tmp"
DATA_DIR.mkdir(exist_ok=True)
TMP_DIR.mkdir(exist_ok=True)
os.environ["TMPDIR"] = str(TMP_DIR)
tempfile.tempdir = None
OMP: Warning #179: Function Can't set size of /tmp file failed:

Hide code cell source

# Import the Python tools and record which ones are installed.
# (Osmosis is a separate command-line program, so we look for it on PATH.)
import pyrosm
from pyrosm import OSM, get_data
import osmnx as ox
import quackosm as qosm
import osmium
from importlib.metadata import version

import re
import subprocess


def osmosis_version(osmosis_bin="osmosis"):
    """Return the Osmosis version (e.g. '0.49.2'), or None if it can't be determined.

    Osmosis has no plain --version flag, but it logs 'Osmosis Version X.Y.Z' to stderr
    at startup, so we run a harmless command (--help) and parse that line.
    """
    try:
        result = subprocess.run(
            [osmosis_bin, "--help"], capture_output=True, text=True, timeout=30,
        )
    except (OSError, subprocess.SubprocessError):
        return None
    match = re.search(r"Osmosis Version (\S+)", result.stdout + result.stderr)
    return match.group(1) if match else None


def osmium_tool_version(osmium_bin="osmium"):
    """Return the osmium-tool version (e.g. '1.19.0'), or None if it can't be determined.

    The osmium command-line tool (separate from the pyosmium bindings) prints
    'osmium version X.Y.Z' on `osmium --version`, so we run it and parse that line.
    """
    try:
        result = subprocess.run(
            [osmium_bin, "--version"], capture_output=True, text=True, timeout=30,
        )
    except (OSError, subprocess.SubprocessError):
        return None
    match = re.search(r"osmium version (\S+)", result.stdout + result.stderr)
    return match.group(1) if match else None


# Command-line tools (found on PATH).
OSMOSIS_BIN = shutil.which("osmosis")
OSMIUM_BIN = shutil.which("osmium")

available_tools = {
    "pyrosm": pyrosm.__version__,
    "osmnx": ox.__version__,
    "quackosm": qosm.__version__,
    "pyosmium": version("osmium"),
    "osmosis": osmosis_version(OSMOSIS_BIN) if OSMOSIS_BIN else None,
    "osmium-tool": osmium_tool_version(OSMIUM_BIN) if OSMIUM_BIN else None,
}


def is_installed(tool):
    """True if `tool` was detected above (used to skip tools that aren't installed)."""
    return bool(available_tools.get(tool))


print("Detected tools:")
for tool, info in available_tools.items():
    print(f"  {tool:9} {info or 'NOT available'}")

# Save the versions next to the results; the R notebook adds the version of osmextract.
VERSIONS_CSV = Path("tool_versions.csv")
versions = (pd.read_csv(VERSIONS_CSV) if VERSIONS_CSV.exists()
            else pd.DataFrame(columns=["tool", "version"]))
versions = versions[~versions["tool"].isin(list(available_tools))]
versions = pd.concat([versions, pd.DataFrame(list(available_tools.items()),
                                             columns=["tool", "version"])], ignore_index=True)
versions.to_csv(VERSIONS_CSV, index=False)
Detected tools:
  pyrosm    0.25.0
  osmnx     2.1.1
  quackosm  0.19.0
  pyosmium  4.3.1
  osmosis   0.49.2
  osmium-tool 1.19.1

Hide code cell source

# Each benchmark run appends one row (a dict) to this list which is turned into a table later
parsing_results = []

RESULTS_CSV = "osm_parsing_results.csv"
RESULT_COLUMNS = ["task", "area", "tool", "seconds", "peak_mb", "features", "status"]


def stored_row(csv, **key):
    """The row `csv` already holds whose columns equal `key`, or None."""
    if not os.path.exists(csv):
        return None
    table = pd.read_csv(csv)
    match = table[(table[list(key)] == pd.Series(key)).all(axis=1)]
    return None if match.empty else match.iloc[-1].to_dict()


def upsert_row(csv, row, key, columns):
    """Write `row` into `csv`, replacing the row with the same values in the `key` columns. The
    table is written to a temporary file that then replaces `csv`, so an interrupted write leaves
    the previous file intact."""
    table = pd.read_csv(csv) if os.path.exists(csv) else pd.DataFrame(columns=columns)
    same = (table[list(key)] == pd.Series({k: row[k] for k in key})).all(axis=1)
    table = pd.concat([table[~same], pd.DataFrame([row], columns=columns)], ignore_index=True)
    handle, temporary = tempfile.mkstemp(suffix=".tmp", dir=os.path.dirname(os.path.abspath(csv)))
    os.close(handle)
    try:
        table.to_csv(temporary, index=False)
        os.replace(temporary, csv)
    except BaseException:
        os.remove(temporary)
        raise


def record_result(row):
    """Upsert one result row into parsing_results and RESULTS_CSV, keyed by (task, area, tool),
    and write the CSV immediately -- so results are exported as each tool finishes, and re-running
    a tool updates its row instead of appending a duplicate."""
    key = (row["task"], row["area"], row["tool"])
    parsing_results[:] = [r for r in parsing_results
                          if (r["task"], r["area"], r["tool"]) != key]
    parsing_results.append(row)
    upsert_row(RESULTS_CSV, row, ("task", "area", "tool"), RESULT_COLUMNS)

Hide code cell source

# Each parse runs in its own process (bench_worker.py), measured by run_monitored.py: the time is
# taken inside the worker, and the peak memory of the process and its child processes is sampled
# (on macOS their physical footprint, which also counts compressed and swapped memory), with a
# per-size timeout. A crash or out-of-memory kill is recorded rather than taking the kernel down.
# Inspired by the osm-python-readers-benchmark (https://github.com/RaczeQ/osm-python-readers-benchmark)
import sys
import json

# run_monitored also logs every run to benchmark.log (follow it with `tail -f benchmark.log`), and
# cool_down pauses after a run, so that the heat of one run does not slow down the next.
from run_monitored import cool_down, run_monitored
from crop_worker import partial_path

BENCH_WORKER = str(Path("bench_worker.py").resolve())
CROP_WORKER = str(Path("crop_worker.py").resolve())
for script in ("bench_worker.py", "crop_worker.py", "run_monitored.py"):
    assert Path(script).exists(), f"{script} must sit next to this notebook"


def monitor_parse(worker_tool, pbf, timeout, extra_args=None, label=None):
    """Run one tool on one PBF in its own process; return its time, the peak memory (MB) of its
    process tree, the feature count and a status. `extra_args` are appended to the worker
    command (osmnx uses them to pass the bounding box it queries); `label` names the run in the
    log. The run is followed by a pause (cool_down)."""
    command = [sys.executable, BENCH_WORKER, worker_tool, str(pbf)]
    command += [str(arg) for arg in extra_args or []]
    run = run_monitored(command, timeout, label=label)
    cool_down(run["wall_seconds"])
    lines = run["stdout"].strip().splitlines()
    if run["status"] != "ok" or not lines:
        status = run["status"] if run["status"] != "ok" else "no output"
        return {"status": status, "seconds": None, "peak_mb": run["peak_mb"], "features": None}
    parsed = json.loads(lines[-1])
    return {"status": "ok", "seconds": round(parsed["seconds"], 2),
            "peak_mb": run["peak_mb"], "features": parsed["features"]}


def print_row(row, unit, after=""):
    """Print one result row: its time, peak memory and feature count, or its failure."""
    if row["status"] == "ok":
        print(f"  {row['tool']:22} {row['seconds']:8.2f} s   {row['peak_mb']:8.0f} MB   "
              f"{int(row['features']):>9,} {unit}")
    else:
        print(f"  {row['tool']:22} {row['status']:>22}   {row['peak_mb']:8.0f} MB peak{after}")


def measure_tool(task, area, label, worker_tool, repeats, extra_args=None, unit="polys"):
    """Run one tool `repeats` times on one area and record its row: the median time and peak
    memory when every run completed; otherwise the failed run's status and peak memory (a failed
    run ends the repeats, and a tool that fails any run counts as failed). A tool whose row
    RESULTS_CSV already holds is not run again; its stored row is printed instead."""
    stored = stored_row(RESULTS_CSV, task=task, area=area.label, tool=label)
    if stored is not None:
        print_row(stored, unit)
        return
    runs = []
    for _ in range(repeats):
        run = monitor_parse(worker_tool, area.pbf, area.timeout, extra_args=extra_args,
                            label=f"{task} | {area.label} | {label}")
        runs.append(run)
        if run["status"] != "ok":
            break   # don't repeat an OOM / timeout / crash
    after = ""
    if runs[-1]["status"] == "ok":
        row = {"task": task, "area": area.label, "tool": label,
               "seconds": round(statistics.median(r["seconds"] for r in runs), 2),
               "peak_mb": round(statistics.median(r["peak_mb"] for r in runs), 1),
               "features": runs[-1]["features"], "status": "ok"}
    else:
        failed = runs[-1]
        row = {"task": task, "area": area.label, "tool": label, "seconds": None,
               "peak_mb": failed["peak_mb"], "features": None, "status": failed["status"]}
        after = f" (after {len(runs) - 1} complete runs)" if len(runs) > 1 else ""
    print_row(row, unit, after)
    record_result(row)

Data#

  • Buildings and Roads are parsed across a ladder of areas of increasing size, so the timings show how each tool scales with input: Kamppi (a neighbourhood clipped out of the Helsinki extract), the Helsinki Region, New York City, Paris, Finland and Spain. pyrosm is measured with both engines. The in-memory engine runs up to Finland and is skipped on Spain, and OSMnx runs on Kamppi and the Helsinki region only.

  • Cropping uses all of Finland (about 770 MB from Geofabrik) as the large input that gets cropped down to the Helsinki region.

Everything is downloaded automatically by pyrosm.get_data(...). The Finland and Spain downloads are large and may take a while the first time.

Hide code cell source

REGION_PBF = get_data("helsinki", directory=DATA_DIR)
NEW_YORK_PBF = get_data("New York City", directory=DATA_DIR)
PARIS_PBF = get_data("paris", directory=DATA_DIR)
FINLAND_PBF = get_data("finland", directory=DATA_DIR)
SPAIN_PBF = get_data("spain", directory=DATA_DIR)
SOUTH_AMERICA_PBF = get_data("south_america", directory=DATA_DIR)

# Helsinki region bounding box (west, south, east, north) for the cropping task.
HELSINKI_BBOX = [24.50, 60.10, 25.25, 60.40]

# Buildings are parsed across a ladder of areas, from a neighbourhood up to a whole country.
# Kamppi is clipped from the Helsinki extract so even the smallest area is a real .osm.pbf that
# every tool reads the same way. `repeats` is the median window (Kamppi/Helsinki 10x, New York City
# 5x, Paris and the country files 3x, South America once; the slow pyosmium streaming reader is further capped to one rep on the
# big areas in the loop below). `timeout` bounds a single isolated parse, scaled to file size.
KAMPPI_BBOX = [24.920, 60.162, 24.942, 60.172]
KAMPPI_PBF = os.path.join(DATA_DIR, "kamppi.osm.pbf")
clip = run_monitored([sys.executable, CROP_WORKER, "pyrosm-fast", REGION_PBF, KAMPPI_PBF,
                      *(str(v) for v in KAMPPI_BBOX)], 600, label="setup | clip Kamppi")
cool_down(clip["wall_seconds"])
if clip["status"] != "ok":
    if os.path.exists(KAMPPI_PBF):
        os.remove(KAMPPI_PBF)   # no partial file for the R notebook to pick up
    raise RuntimeError(f"Clipping Kamppi failed: {clip['status']}")

Area = namedtuple("Area", "label pbf repeats timeout")
AREAS = [
    Area("Kamppi",          KAMPPI_PBF,        10,  120),
    Area("Helsinki region", REGION_PBF,        10,  300),
    Area("New York City",   NEW_YORK_PBF,       5,  900),
    Area("Paris",           PARIS_PBF,          3, 1500),
    Area("Finland",         FINLAND_PBF,        3, 3600),
    Area("Spain",           SPAIN_PBF,          3, 3600),
    Area("South America",   SOUTH_AMERICA_PBF,  1, 3600),
]

# Share the file paths (relative to this folder), repeats and timeouts with the R companion
# (osmextract_benchmark_scaling.ipynb) so it benchmarks osmextract on the very same files.
pd.DataFrame(
    [(a.label, os.path.relpath(a.pbf, HERE), a.repeats, a.timeout) for a in AREAS],
    columns=["area", "path", "repeats", "timeout"],
).to_csv("scaling_areas.csv", index=False)

print("Region PBF :", os.path.relpath(REGION_PBF, HERE), f"({os.path.getsize(REGION_PBF)/1e6:.1f} MB)")
print("Finland PBF:", os.path.relpath(FINLAND_PBF, HERE), f"({os.path.getsize(FINLAND_PBF)/1e6:.1f} MB)")
print("\nBuildings area ladder:")
for area in AREAS:
    print(f"  {area.label:16} {os.path.relpath(area.pbf, HERE)}  ({os.path.getsize(area.pbf)/1e6:7.1f} MB)")
Region PBF : data/Helsinki.osm.pbf (64.9 MB)
Finland PBF: data/finland-latest.osm.pbf (771.0 MB)

Buildings area ladder:
  Kamppi           data/kamppi.osm.pbf  (    6.2 MB)
  Helsinki region  data/Helsinki.osm.pbf  (   64.9 MB)
  New York City    data/newyorkcity.osm.pbf  (  153.2 MB)
  Paris            data/Paris.osm.pbf  (  242.5 MB)
  Finland          data/finland-latest.osm.pbf  (  771.0 MB)
  Spain            data/spain-latest.osm.pbf  ( 1490.5 MB)
  South America    data/south-america-latest.osm.pbf  ( 4139.1 MB)

Task 1 — Parse buildings into a GeoDataFrame: time and memory across area sizes#

Every tool selects the building-tagged features and reads them into a GeoDataFrame (osmextract into an R sf data frame), repeated across the area ladder (Kamppi → Spain). Following the practice of the osm-python-readers-benchmark, each parse runs in its own process while run_monitored.py samples the peak memory of its process tree (the physical footprint on macOS) alongside the time (with a per-size timeout). Also, a crash or out-of-memory kill is recorded. pyrosm’s out-of-core engine (engine="out_of_core", workers="auto") can read files that no longer fit in RAM, because it streams the data through temporary files on disk. Its result cache is cleared before each read, so that every measurement includes the parse. It runs the full ladder, as QuackOSM (DuckDB) does. The in-memory engine (engine="in_memory") is run up to Finland and skipped on Spain, where it is expected to exceed the 24 GB of RAM. pyosmium (a streaming reader) and osmium-tool (a command-line tool; here it exports GeoJSON, which is then read with GeoPandas) read the local files too: pyosmium is run on the four smaller areas (Kamppi → Paris) and osmium-tool up to Finland. OSMnx downloads from the public Overpass API rather than reading the local file, so its time includes the download and the Overpass server’s work and is not directly comparable to the local-file readers; its peak memory covers only the local OSMnx process. The public Overpass API has performance issues under heavy load, which shows in the results: during this benchmark (October 2026) OSMnx fetched the buildings of Kamppi (66 s) and the Helsinki region (34 s), but the Overpass server refused its requests for the road networks of these two areas, and earlier requests for both buildings and roads on New York City and Paris timed out. To keep the load on the public Overpass service reasonable, OSMnx is run once on each of the two smallest areas only. In the previous version of this benchmark (June 2026, with older versions of the tools), OSMnx fetched the buildings of Kamppi in 4 s and of the Helsinki region in 46 s, and the road networks of all four areas: Kamppi in 26 s, the Helsinki region in 93 s, New York City in 248 s and Paris in 159 s.

Each area runs in its own cell below, so you can run and inspect them one at a time; re-running an area’s cell measures only the tools whose results are not stored yet (delete a row from osm_parsing_results.csv to measure it again).

Hide code cell source

# Task 1 setup: the buildings readers, and a helper that benchmarks every applicable tool on a
# single area's PBF (isolated subprocess; median time + peak memory). Each area is then run in
# its own cell below. pyrosm is measured with both engines; the in-memory engine is attempted on
# every area so its out-of-memory point on the country files is recorded. osmium-tool (a
# GeoJSON-export CLI) and OSMnx (Overpass API) are shown on the small areas only; the slow
# pyosmium streaming reader runs a single rep on the big areas.
SCALE_READERS = [
    # label,                    worker tool,                     only on these areas (None = all)
    ("pyrosm (in-memory)",      "pyrosm-in-memory",            {"Kamppi", "Helsinki region", "New York City", "Paris", "Finland"}),
    ("pyrosm (out-of-core)",    "pyrosm-out-of-core",          None),
    ("quackosm (with columns)", "quackosm-with-columns",       None),
    ("quackosm (no columns)",   "quackosm-no-columns",         None),
    ("pyosmium",                "pyosmium",                    {"Kamppi", "Helsinki region", "New York City", "Paris"}),
    ("osmium-tool",             "osmium-tool",                 {"Kamppi", "Helsinki region", "New York City", "Paris", "Finland"}),
    ("osmnx",                   "osmnx",                       {"Kamppi", "Helsinki region"}),
]
SMALL_AREAS = {"Kamppi", "Helsinki region"}
AREA = {area.label: area for area in AREAS}

# OSMnx queries Overpass for a bounding box rather than reading the file; use the same extent as
# the local data (Kamppi's clip box; Helsinki's data extent, read once and cached).
_OSMNX_BBOX = {"Kamppi": KAMPPI_BBOX}


def _osmnx_bbox(area):
    """The extent of an area's buildings, read in a separate process (measured and followed by
    a pause, like the benchmark runs) so that this kernel does not hold the data."""
    if area.label not in _OSMNX_BBOX:
        script = ("import json, sys; from pyrosm import OSM; "
                  "print(json.dumps([float(v) for v in OSM(sys.argv[1]).get_buildings().total_bounds]))")
        run = run_monitored([sys.executable, "-c", script, area.pbf], area.timeout,
                            label=f"setup | extent of {area.label}")
        cool_down(run["wall_seconds"])
        lines = run["stdout"].strip().splitlines()
        if run["status"] != "ok" or not lines:
            raise RuntimeError(f"Reading the extent of {area.label} failed: {run['status']}")
        _OSMNX_BBOX[area.label] = json.loads(lines[-1])
    return _OSMNX_BBOX[area.label]


def run_buildings_for_area(area):
    """Benchmark every applicable tool on one area and record the rows. A tool whose row is
    already stored is not run again, so each area cell can be run on its own."""
    print(f"{area.label} ({os.path.getsize(area.pbf)/1e6:.0f} MB, up to {area.repeats}x, "
          f"timeout {area.timeout}s):")
    for label, worker_tool, only_areas in SCALE_READERS:
        if only_areas is not None and area.label not in only_areas:
            continue
        extra_args = _osmnx_bbox(area) if worker_tool == "osmnx" else None
        if worker_tool == "osmnx":
            reps = 1                                     # one live Overpass query is enough
        elif worker_tool in ["pyosmium", "osmium-tool"] and area.label not in SMALL_AREAS:
            reps = 1                                     # cap the slow streaming reader on big files
        else:
            reps = area.repeats
        measure_tool("buildings", area, label, worker_tool, reps, extra_args=extra_args, unit="polys")
# Kamppi (smallest area) - 10 iterations each tool
run_buildings_for_area(AREA["Kamppi"])
Kamppi (6 MB, up to 10x, timeout 120s):
  pyrosm (in-memory)         0.80 s        125 MB         684 polys
  pyrosm (out-of-core)       0.81 s        127 MB         684 polys
  quackosm (with columns)    10.35 s        291 MB         682 polys
  quackosm (no columns)      9.99 s        291 MB         682 polys
  pyosmium                   0.58 s         90 MB         682 polys
  osmium-tool                0.68 s        664 MB         638 polys
  osmnx                     65.64 s        231 MB         685 polys
# Helsinki region - 10 iterations each tool
run_buildings_for_area(AREA["Helsinki region"])
Helsinki region (65 MB, up to 10x, timeout 300s):
  pyrosm (in-memory)         2.45 s       1008 MB     187,421 polys
  pyrosm (out-of-core)       2.06 s        597 MB     187,421 polys
  quackosm (with columns)    18.48 s       4597 MB     187,452 polys
  quackosm (no columns)     12.71 s       1055 MB     187,452 polys
  pyosmium                  13.79 s       3143 MB     187,452 polys
  osmium-tool               10.47 s       2969 MB     186,971 polys
  osmnx                     34.16 s       4087 MB     187,952 polys
# New York City - 5 iterations except pyosmium/osmium-tool run only once (timeout at 15 minutes)
run_buildings_for_area(AREA["New York City"])
New York City (153 MB, up to 5x, timeout 900s):
  pyrosm (in-memory)        10.70 s       5573 MB   1,602,597 polys
  pyrosm (out-of-core)       4.53 s       2286 MB   1,602,597 polys
  quackosm (with columns)    77.53 s      24012 MB   1,602,652 polys
  quackosm (no columns)     21.75 s       3376 MB   1,602,652 polys
  pyosmium                              timeout      18388 MB peak
  osmium-tool              102.94 s      30633 MB   1,600,058 polys
# Paris - pyosmium/osmium-tool run only once (timeout at 20 minutes)
run_buildings_for_area(AREA["Paris"])
Paris (242 MB, up to 3x, timeout 1500s):
  pyrosm (in-memory)        13.92 s       6663 MB   1,888,463 polys
  pyrosm (out-of-core)       5.29 s       2944 MB   1,888,463 polys
  quackosm (with columns)   120.88 s      35740 MB   1,888,696 polys
  quackosm (no columns)     24.09 s       5587 MB   1,888,696 polys
  pyosmium                              timeout      26515 MB peak
  osmium-tool              146.34 s      44424 MB   1,873,130 polys
# Finland (country; in-memory engine might run out of memory)
run_buildings_for_area(AREA["Finland"])
Finland (771 MB, up to 3x, timeout 3600s):
  pyrosm (in-memory)        40.48 s      17372 MB   4,379,257 polys
  pyrosm (out-of-core)       9.80 s       5145 MB   4,379,257 polys
  quackosm (with columns)   438.96 s     103274 MB   4,379,400 polys
  quackosm (no columns)     41.46 s       5958 MB   4,379,400 polys
  osmium-tool               OOM/crash (exit -9)     121574 MB peak
# Spain (large country; in-memory engine expected to run out of memory)
run_buildings_for_area(AREA["Spain"])
Spain (1491 MB, up to 3x, timeout 3600s):
  pyrosm (out-of-core)      24.10 s       7913 MB   5,731,551 polys
  quackosm (with columns)    OOM/crash (exit -9)     147705 MB peak
  quackosm (no columns)     66.20 s      19742 MB   5,735,125 polys

Task 2 — Parse the road network into a GeoDataFrame: time and memory across area sizes#

The same comparison as buildings, for the road network: every tool extracts highway=* ways as lines (LineString/MultiLineString) and we record time and peak memory across the area ladder, each parse in its own isolated subprocess. pyrosm uses get_data_by_custom_criteria({"highway": True}) with both engines. The skips are mostly the same as in the buildings task: in-memory pyrosm, osmium-tool and pyosmium are not run on Spain (they would run out of memory or time out), and OSMnx is run on Kamppi and the Helsinki region only; its road-network requests to the public Overpass API failed during this benchmark (see Task 1). OSMnx returns a simplified routing graph rather than the raw ways, so even a successful request would give a line count that is not directly comparable. Each area runs in its own cell below; re-running an area’s cell measures only the tools whose road results are not stored yet.

Hide code cell source

# Task 2 setup: benchmark the road network (highway=* lines) with the same isolated-subprocess
# harness as buildings (median time + peak memory). Each area runs in its own cell below. Reuses
# monitor_parse, AREA, SMALL_AREAS and _osmnx_bbox from the buildings setup. The skips match
# buildings; the worker tools are the "net-*" entries in bench_worker.py (which count lines).
SCALE_READERS_NET = [
    # label,                     worker tool,                  only on these areas (None = all)
    ("pyrosm (in-memory)",       "net-pyrosm-in-memory",       {"Kamppi", "Helsinki region", "New York City", "Paris", "Finland"}),
    ("pyrosm (out-of-core)",     "net-pyrosm-out-of-core",      None),
    ("quackosm (with columns)",  "net-quackosm-with-columns",   None),
    ("quackosm (no columns)",    "net-quackosm-no-columns",     None),
    ("pyosmium",                 "net-pyosmium",                {"Kamppi", "Helsinki region", "New York City", "Paris", "Finland"}),
    ("osmium-tool",              "net-osmium-tool",             {"Kamppi", "Helsinki region", "New York City", "Paris", "Finland"}),
    ("osmnx",                    "net-osmnx",                   {"Kamppi", "Helsinki region"}),
]


def run_network_for_area(area):
    """Benchmark every applicable tool's road-network read on one area (isolated subprocess; median
    time + peak memory). A tool whose row is already
    stored is not run again."""
    print(f"{area.label} ({os.path.getsize(area.pbf)/1e6:.0f} MB, up to {area.repeats}x, "
          f"timeout {area.timeout}s):")
    for label, worker_tool, only_areas in SCALE_READERS_NET:
        if only_areas is not None and area.label not in only_areas:
            continue
        extra_args = _osmnx_bbox(area) if worker_tool == "net-osmnx" else None
        if worker_tool == "net-osmnx":
            reps = 1                                     # one live Overpass query is enough
        elif worker_tool == "net-pyosmium" and area.label not in SMALL_AREAS:
            reps = 1                                     # cap the slow streaming reader on big files
        else:
            reps = area.repeats
        measure_tool("roads", area, label, worker_tool, reps, extra_args=extra_args, unit="lines")
# Kamppi (smallest area)
run_network_for_area(AREA["Kamppi"])
Kamppi (6 MB, up to 10x, timeout 120s):
  pyrosm (in-memory)         0.81 s        131 MB       4,795 lines
  pyrosm (out-of-core)       0.82 s        135 MB       4,795 lines
  quackosm (with columns)    10.96 s        341 MB       4,794 lines
  quackosm (no columns)     10.02 s        291 MB       4,794 lines
  pyosmium                   0.66 s        119 MB       4,854 lines
  osmium-tool                0.80 s       1149 MB       4,800 lines
  osmnx                  error (exit 1): requests.exceptions.ConnectionError: HTTPSConnectionPool(host='overpass-api.de', ... er (Caused by NewConnectionError("HTTPSConnection(host='overpass-api.de', port=443): Failed to establish a new connection: [Errno 61] Connection refused"))        224 MB peak
# Helsinki region 
run_network_for_area(AREA["Helsinki region"])
Helsinki region (65 MB, up to 10x, timeout 300s):
  pyrosm (in-memory)         2.62 s       1079 MB     305,148 lines
  pyrosm (out-of-core)       2.17 s        660 MB     305,148 lines
  quackosm (with columns)    57.50 s      12153 MB     305,060 lines
  quackosm (no columns)     13.01 s       1044 MB     305,060 lines
  pyosmium                  62.24 s      10144 MB     308,683 lines
  osmium-tool               29.98 s       9792 MB     305,327 lines
  osmnx                  error (exit 1): requests.exceptions.ConnectionError: HTTPSConnectionPool(host='overpass-api.de', ... er (Caused by NewConnectionError("HTTPSConnection(host='overpass-api.de', port=443): Failed to establish a new connection: [Errno 61] Connection refused"))        222 MB peak
# New York
run_network_for_area(AREA["New York City"])
New York City (153 MB, up to 5x, timeout 900s):
  pyrosm (in-memory)         5.48 s       2834 MB     674,751 lines
  pyrosm (out-of-core)       2.84 s        994 MB     674,751 lines
  quackosm (with columns)    43.44 s      12255 MB     674,641 lines
  quackosm (no columns)     16.19 s       1872 MB     674,641 lines
  pyosmium                  64.27 s      10693 MB     677,387 lines
  osmium-tool               34.86 s      10323 MB     674,870 lines
# Paris 
run_network_for_area(AREA["Paris"])
Paris (242 MB, up to 3x, timeout 1500s):
  pyrosm (in-memory)         6.04 s       3119 MB     639,431 lines
  pyrosm (out-of-core)       3.00 s        995 MB     639,431 lines
  quackosm (with columns)    69.02 s      18458 MB     637,311 lines
  quackosm (no columns)     17.69 s       1911 MB     637,311 lines
  pyosmium                  85.87 s      14205 MB     649,388 lines
  osmium-tool               44.73 s      13674 MB     639,950 lines
# Finland 
run_network_for_area(AREA["Finland"])
Finland (771 MB, up to 3x, timeout 3600s):
  pyrosm (in-memory)        25.26 s      14075 MB   2,224,133 lines
  pyrosm (out-of-core)       8.25 s       3626 MB   2,224,133 lines
  quackosm (with columns)   660.51 s     110100 MB   2,223,189 lines
  quackosm (no columns)     35.81 s      15815 MB   2,223,189 lines
  pyosmium                              timeout      57484 MB peak
  osmium-tool              357.69 s     102909 MB   2,225,136 lines
# Spain 
run_network_for_area(AREA["Spain"])
Spain (1491 MB, up to 3x, timeout 3600s):
  pyrosm (out-of-core)      22.33 s      10595 MB   5,812,581 lines
  quackosm (with columns)    OOM/crash (exit -9)     148696 MB peak
  quackosm (no columns)    101.06 s      22058 MB   5,788,516 lines

Head-to-head: pyrosm vs QuackOSM, geometry + key only#

In the comparison above, pyrosm and QuackOSM do not do exactly the same work: QuackOSM either turns every tag into a GeoDataFrame column, which is expensive, or returns no tag columns at all. To compare them on equal footing, both parse only the geometry and the key tag (building) into a GeoDataFrame, with no other tag columns. pyrosm (out-of-core) uses get_data_by_custom_criteria({"building": True}, tags_as_columns=["building"], keep_other_tags=False) and QuackOSM uses tags_filter={"building": True}, keep_all_tags=False. Both read nodes, ways and relations. The cell below runs this across every area and records the rows under their own task (buildings (geometry + key)).

Hide code cell source

# Head-to-head: pyrosm (out-of-core) vs quackosm parsing ONLY geometry + the key ("building"), so
# both return the same minimal output (geometry + the key column, no other tag columns) and are
# directly comparable. Runs across every area; results are recorded under their own task.
GEOM_TASK = "buildings (geometry + key)"
GEOM_KEY = "building"
GEOM_READERS = [
    ("pyrosm (out-of-core)", "geom-pyrosm-out-of-core"),
    ("quackosm",             "geom-quackosm"),
]

print(f"Head-to-head: geometry + '{GEOM_KEY}' only (pyrosm out-of-core vs quackosm):\n")
for area in AREAS:
    print(f"{area.label} ({os.path.getsize(area.pbf)/1e6:.0f} MB, up to {area.repeats}x):")
    for label, worker_tool in GEOM_READERS:
        measure_tool(GEOM_TASK, area, label, worker_tool, area.repeats, extra_args=[GEOM_KEY], unit="polys")
    print()
Head-to-head: geometry + 'building' only (pyrosm out-of-core vs quackosm):

Kamppi (6 MB, up to 10x):
  pyrosm (out-of-core)       0.82 s        126 MB         684 polys
  quackosm                  10.35 s        295 MB         682 polys

Helsinki region (65 MB, up to 10x):
  pyrosm (out-of-core)       1.77 s        494 MB     187,421 polys
  quackosm                  13.29 s       1044 MB     187,452 polys

New York City (153 MB, up to 5x):
  pyrosm (out-of-core)       3.56 s       1852 MB   1,602,597 polys
  quackosm                  21.40 s       3374 MB   1,602,652 polys

Paris (242 MB, up to 3x):
  pyrosm (out-of-core)       4.53 s       2430 MB   1,888,463 polys
  quackosm                  24.52 s       5597 MB   1,888,696 polys

Finland (771 MB, up to 3x):
  pyrosm (out-of-core)       9.04 s       4140 MB   4,379,257 polys
  quackosm                  41.70 s       5970 MB   4,379,400 polys

Spain (1491 MB, up to 3x):
  pyrosm (out-of-core)      22.86 s       6735 MB   5,731,551 polys
  quackosm                  66.14 s      19761 MB   5,735,125 polys

South America (4139 MB, up to 1x):
  pyrosm (out-of-core)      77.76 s      24174 MB   25,616,024 polys
  quackosm                 341.80 s      25736 MB   25,618,595 polys

Task 3 — Crop a large PBF to a region and save to disk#

Crop the Finland PBF down to the Helsinki region bounding box and write a new .osm.pbf. All four croppers keep complete ways (ways crossing the box keep all their nodes). Each crop runs in its own process, and its result is then read back and its buildings counted, as a check that no buildings were lost.

OSMnx and QuackOSM are not part of this task: OSMnx does not handle local PBF files, and QuackOSM converts PBF to GeoParquet rather than writing a cropped .osm.pbf.

Here each tool runs on a single thread: pyrosm with workers=1, and pyosmium and osmium-tool with OSMIUM_POOL_THREADS=1. Osmosis is the exception, as its Java pipeline always uses several threads. The next section gives the tools several threads (the number of CPU cores minus two, at most 8) to show how each one scales.

Hide code cell source

# Crop the large Finland PBF down to the Helsinki-region bounding box and write a new .osm.pbf,
# each tool in its own process (crop_worker.py), measured like the parses. Every tool keeps
# complete ways; the result is read back in another process, outside the measured crop, and its
# buildings counted, as a check for lost buildings.
crop_dir = str(TMP_DIR)
CROP_TIMEOUT = 3600
CROP_CSV = "osmcrop_results.csv"
CROP_COLUMNS = ["run", "tool", "seconds", "peak_mb", "out_mb", "buildings", "status"]
crop_results = []


def print_crop(row):
    """Print one crop row: its time, peak memory, output size and buildings, or its failure."""
    if row["status"] == "ok":
        print(f"  {row['run']:32} {row['seconds']:7.1f} s   {row['peak_mb']:8.0f} MB   "
              f"{row['out_mb']:6.1f} MB out   {int(row['buildings']):,} buildings")
    else:
        print(f"  {row['run']:32} {row['status']}")


def run_crop(results, label, tool, worker_tool, workers=1, threads=None):
    """Crop with one tool in its own process and record its time, peak memory and output size,
    and the buildings read back from the output in another process. `workers` are pyrosm's worker threads; `threads`
    sets libosmium's thread pool (OSMIUM_POOL_THREADS) for pyosmium and osmium-tool. The crop is
    followed by a pause (cool_down). A crop whose row CROP_CSV already holds is not run again;
    its stored row is used instead."""
    stored = stored_row(CROP_CSV, run=label)
    if stored is not None:
        print_crop(stored)
        results.append(stored)
        return
    if not is_installed(tool):
        print(f"  {label:32} not installed - skipped")
        return
    output = os.path.join(crop_dir, f"crop_{worker_tool}_{workers}w_{threads or 'default'}t.osm.pbf")
    env = dict(os.environ)
    if threads is not None:
        env["OSMIUM_POOL_THREADS"] = str(threads)
    command = [sys.executable, CROP_WORKER, worker_tool, FINLAND_PBF, output,
               *(str(v) for v in HELSINKI_BBOX), str(workers)]
    try:
        run = run_monitored(command, CROP_TIMEOUT, env=env, label=f"crop | {label}")
    except BaseException:
        if os.path.lexists(partial_path(output)):
            os.remove(partial_path(output))   # the temporary file of an interrupted crop
        raise
    row = {"run": label, "tool": tool, "seconds": None, "peak_mb": run["peak_mb"],
           "out_mb": None, "buildings": None, "status": run["status"]}
    try:
        lines = run["stdout"].strip().splitlines()
        if run["status"] == "ok" and lines:
            parsed = json.loads(lines[-1])
            row.update(seconds=round(parsed["seconds"], 1), out_mb=parsed["out_mb"])
            try:
                count = subprocess.run([sys.executable, CROP_WORKER, "count", output],
                                       capture_output=True, text=True, timeout=CROP_TIMEOUT,
                                       check=True)
                buildings = json.loads(count.stdout.strip().splitlines()[-1])["buildings"]
                if not isinstance(buildings, int) or isinstance(buildings, bool) or buildings < 0:
                    raise ValueError(f"not a building count: {buildings!r}")
                row["buildings"] = buildings
            except (subprocess.SubprocessError, ValueError, IndexError, KeyError, TypeError):
                row["status"] = "output could not be read back"
        elif run["status"] == "ok":
            row["status"] = "no output"
        if run["status"] != "ok" and os.path.lexists(partial_path(output)):
            os.remove(partial_path(output))   # the temporary file of a killed crop
        print_crop(row)
        upsert_row(CROP_CSV, row, ("run",), CROP_COLUMNS)
        results.append(row)
    finally:
        cool_down(run["wall_seconds"])


print("Task 3 - crop Finland to the Helsinki region (buildings = count read back):\n")

# pyrosm on one worker, pyosmium and osmium-tool with one thread in libosmium's pool
run_crop(crop_results, "pyrosm", "pyrosm", "pyrosm")
run_crop(crop_results, "pyosmium", "pyosmium", "pyosmium", threads=1)
run_crop(crop_results, "osmium-tool", "osmium-tool", "osmium-tool", threads=1)
run_crop(crop_results, "osmosis", "osmosis", "osmosis")
Task 3 - crop Finland to the Helsinki region (buildings = count read back):

  pyrosm                              15.9 s        427 MB     60.9 MB out   225,570 buildings
  pyosmium                           234.8 s        882 MB     61.7 MB out   225,570 buildings
  osmium-tool                         16.7 s       3937 MB     61.7 MB out   225,570 buildings
  osmosis                            189.4 s        441 MB     61.3 MB out   225,570 buildings

Task 3 with several threads — does parallelism speed up the crop?#

Re-run the Finland → Helsinki crop in parallel, using each tool’s own mechanism:

  • pyrosm crops on several threads with to_pbf(..., workers=N), compared at workers=1 and workers=N, where N is the number of CPU cores minus two, at most 8 (8 on this laptop).

  • pyosmium uses libosmium’s thread pool (OSMIUM_POOL_THREADS) only to (de)compress the PBF blocks. Its extract loop is single-threaded Python, so it gains little from more threads.

  • osmium-tool uses the same thread pool, but the rest of its extract runs in C++, so it scales the best of the three.

  • Osmosis has no thread setting for this crop, so it is left out.

Each output is read back and its buildings counted, as in Task 3.

Hide code cell source

# Re-run the crop in parallel, using each tool's own mechanism, to see whether more
# workers / threads actually help:
#   - pyrosm crops on several THREADS via to_pbf(workers=N).
#   - pyosmium relies on libosmium's PBF (de)compression THREAD POOL (OSMIUM_POOL_THREADS).
#     The pool threads only the (de)compression and the extract loop is single-threaded
#     Python, so it gains little from one to eight threads.
#   - osmium-tool uses the same libosmium thread pool, and the rest of its extract runs in
#     native C++ rather than a Python loop, so it scales best of the three.
#   - Osmosis has no worker knob for a bbox crop, so it is left out of this comparison.

# The number of CPU cores minus two, at most 8.
N_WORKERS = min(8, max(1, (os.cpu_count() or 1) - 2))
parallel_crop_results = []

print("Task 3 in parallel - more workers / threads:\n")

run_crop(parallel_crop_results, f"pyrosm, {N_WORKERS} workers (fast-mode)", "pyrosm", "pyrosm-fast",
         workers=N_WORKERS)
run_crop(parallel_crop_results, f"pyrosm, {N_WORKERS} workers (compact)", "pyrosm", "pyrosm",
         workers=N_WORKERS)
run_crop(parallel_crop_results, f"pyosmium, {N_WORKERS} threads", "pyosmium", "pyosmium",
         threads=N_WORKERS)
run_crop(parallel_crop_results, f"osmium-tool, {N_WORKERS} threads", "osmium-tool", "osmium-tool",
         threads=N_WORKERS)

if parallel_crop_results:
    display(pd.DataFrame(parallel_crop_results))
Task 3 in parallel - more workers / threads:

  pyrosm, 8 workers (fast-mode)        4.4 s        479 MB     85.3 MB out   225,570 buildings
  pyrosm, 8 workers (compact)          6.4 s        478 MB     60.9 MB out   225,570 buildings
  pyosmium, 8 threads                228.0 s        923 MB     61.7 MB out   225,570 buildings
  osmium-tool, 8 threads               3.7 s       3972 MB     61.7 MB out   225,570 buildings
run tool seconds peak_mb out_mb buildings status
0 pyrosm, 8 workers (fast-mode) pyrosm 4.4 478.6 85.3 225570 ok
1 pyrosm, 8 workers (compact) pyrosm 6.4 478.1 60.9 225570 ok
2 pyosmium, 8 threads pyosmium 228.0 922.8 61.7 225570 ok
3 osmium-tool, 8 threads osmium-tool 3.7 3972.2 61.7 225570 ok

Collect all the Python tool results and visualise#

# Results were exported incrementally as each tool finished (record_result). Load them back here
# for the tables and charts; re-running this cell picks up whatever has been collected so far.
parsing_df = (pd.read_csv(RESULTS_CSV) if os.path.exists(RESULTS_CSV)
              else pd.DataFrame(columns=RESULT_COLUMNS))

Results: tables and visualisations#

# osmextract is an R package; its results come from the companion notebook
# osmextract_benchmark_scaling.ipynb (R kernel), which writes osmextract_scaling_results.csv
# (buildings and the road network across the area ladder, with time + peak memory) next to this
# file. Load it so osmextract appears in the tables and charts.
osmextract_csv = Path("osmextract_scaling_results.csv")
if osmextract_csv.exists():
    rows = pd.read_csv(osmextract_csv)
    print(f"Loaded {len(rows)} osmextract row(s) from {osmextract_csv}")
    parsing_df = pd.concat([parsing_df, rows], ignore_index=True)
else:
    print("osmextract_scaling_results.csv not found - run osmextract_benchmark_scaling.ipynb (R).")
Loaded 12 osmextract row(s) from osmextract_scaling_results.csv
parsing_table = parsing_df
print("Parsing tasks (seconds = median wall-clock; features = normalised count):")
display(parsing_table)
#crop_results = False
if crop_results:
    # Combine all results together
    all_crop_results = crop_results + parallel_crop_results
    crop_table = pd.DataFrame(all_crop_results)
    print("\nCropping task:")
    display(crop_table)
Parsing tasks (seconds = median wall-clock; features = normalised count):
task area tool seconds peak_mb features status
0 buildings Kamppi quackosm (with columns) 10.35 290.8 682.0 ok
1 buildings Kamppi quackosm (no columns) 9.99 291.0 682.0 ok
2 buildings Kamppi pyosmium 0.58 90.0 682.0 ok
3 buildings Kamppi osmium-tool 0.68 663.5 638.0 ok
4 buildings Helsinki region quackosm (with columns) 18.48 4597.1 187452.0 ok
... ... ... ... ... ... ... ...
94 roads Helsinki region osmextract 3.49 717.0 305177.0 ok
95 roads New York City osmextract 7.31 1250.7 674850.0 ok
96 roads Paris osmextract 8.04 1223.5 639805.0 ok
97 roads Finland osmextract 35.29 4234.0 2224380.0 ok
98 roads Spain osmextract 121.12 11203.5 5813702.0 ok

99 rows × 7 columns

Cropping task:
run tool seconds peak_mb out_mb buildings status
0 pyrosm pyrosm 15.9 427.3 60.9 225570 ok
1 pyosmium pyosmium 234.8 882.5 61.7 225570 ok
2 osmium-tool osmium-tool 16.7 3936.7 61.7 225570 ok
3 osmosis osmosis 189.4 440.6 61.3 225570 ok
4 pyrosm, 8 workers (fast-mode) pyrosm 4.4 478.6 85.3 225570 ok
5 pyrosm, 8 workers (compact) pyrosm 6.4 478.1 60.9 225570 ok
6 pyosmium, 8 threads pyosmium 228.0 922.8 61.7 225570 ok
7 osmium-tool, 8 threads osmium-tool 3.7 3972.2 61.7 225570 ok

Area-level visualisations across all tools#

Hide code cell source

# ---- Styling for the result charts ----
plt.rcParams.update({
    "figure.facecolor": "white", "savefig.facecolor": "white",
    "savefig.dpi": 200, "savefig.bbox": "tight",
    "axes.edgecolor": "#888888", "axes.linewidth": 0.8,
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.grid": True, "axes.axisbelow": True,
    "grid.color": "#ECECF1", "grid.linewidth": 1.0,
    "axes.titlesize": 13, "axes.titleweight": "bold",
    "axes.labelsize": 11, "axes.labelcolor": "#333333",
    "xtick.color": "#333333", "ytick.color": "#333333",
})

# pyrosm is highlighted; every other tool shares one muted colour.
PYROSM_COLOR = "#2A849D"
OTHER_COLOR = "#BC778F"

def bar_colors(tools):
    return [PYROSM_COLOR if tool == "pyrosm" else OTHER_COLOR for tool in tools]

# Result figures are written here (relative to this notebook).
FIGURE_DIR = "figures"
os.makedirs(FIGURE_DIR, exist_ok=True)

Hide code cell source

import math
import re

# One figure per task and metric
# Ensure that the AREAS include every area
AREAS = [
    Area("Kamppi",          KAMPPI_PBF,        10,  120),
    Area("Helsinki region", REGION_PBF,        10,  300),
    Area("New York City",   NEW_YORK_PBF,       5,  900),
    Area("Paris",           PARIS_PBF,          3, 1500),
    Area("Finland",         FINLAND_PBF,        3, 3600),
    Area("Spain",           SPAIN_PBF,          3, 3600),
    Area("South America",   SOUTH_AMERICA_PBF,  1, 3600),
]

area_order = [a.label for a in AREAS]
AREA_TIMEOUT = {a.label: a.timeout for a in AREAS}
TOOL_ORDER = ["pyrosm (in-memory)", "pyrosm (out-of-core)", "quackosm (with columns)", "quackosm (no columns)", "pyosmium",
              "osmium-tool", "osmnx", "osmextract"]
SPECIAL_TOOL = "quackosm (no columns)"   # not comparable: tags kept as JSON, not exploded to columns
SPECIAL_COLOR = "#9E9E9E"
SPECIAL_NOTE = ('* "quackosm (no columns)" does not convert tags into columns (instead tags are stored as JSONs), \n'
                "thus its time and memory are not directly comparable with the other tools.")


def _failed(row):
    """Whether the run stopped with an error, so the memory sampled until then is not shown."""
    return row is not None and str(row["status"]).startswith("error")


def _status_note(row, area):
    """Why a tool has no value for this metric, written where its bar would be."""
    if row is None:
        return "Not measured"
    status = str(row["status"])
    if _failed(row):
        reason = status.split(": ", 1)[1] if ": " in status else ""
        name = reason.split(":", 1)[0].rsplit(".", 1)[-1] or "unknown"
        detail = re.search(r"\[Errno -?\d+\] ([^'\")]+)", reason)
        return "Error: " + name + (f" ({detail.group(1).strip()})" if detail else "")
    if status == "timeout":
        return f"Timeout after {int(round(AREA_TIMEOUT.get(area, 0) / 60))} min"
    if "OOM" in status:
        return "Out of memory"
    return "Not measured"


def _incomplete_tag(row):
    """Suffix marking a value whose run did not finish, so a peak-memory bar for a timed-out
    or killed run is shown but not read as a completed measurement."""
    status = "ok" if row is None else str(row["status"])
    if status == "timeout":
        return " (timed out)"
    if "OOM" in status:
        return " (out of memory)"
    return ""


def plot_per_area(task, metric, xlabel, fmt, suptitle, png):
    table = (parsing_table[parsing_table["task"] == task]
             .drop_duplicates(subset=["area", "tool"], keep="last"))
    areas = [a for a in area_order if a in set(table["area"])]
    if not areas:
        print(f"No rows for task={task!r} yet.")
        return

    fig, axes = plt.subplots(len(areas), 1, figsize=(9, 2.7 * len(areas)), squeeze=False)
    for ax, area in zip(axes[:, 0], areas):
        sub = table[table["area"] == area].set_index("tool")
        entries = []
        for tool in TOOL_ORDER:
            row = sub.loc[tool] if tool in sub.index else None
            if row is not None and pd.notna(row[metric]) and not _failed(row):
                # A captured value is a bar -- including an incomplete run (timeout / OOM) whose
                # peak memory was still sampled; it is faded and its label tagged below.
                entries.append((tool, float(row[metric]), None, _incomplete_tag(row)))
            else:
                # No value for this metric -> a grey note explains why.
                entries.append((tool, math.nan, _status_note(row, area), ""))

        # Sort the comparable tools by value; pin the not-comparable "no columns" variant to the bottom.
        special = [e for e in entries if e[0] == SPECIAL_TOOL]
        normal = [e for e in entries if e[0] != SPECIAL_TOOL]
        normal.sort(key=lambda e: e[1] if e[2] is None else math.inf)
        entries = normal + special

        n = len(entries)
        for i, (tool, value, note, tag) in enumerate(entries):
            y = n - 1 - i                          # fastest / lowest at the top
            if note is None:
                if tool == SPECIAL_TOOL:
                    color = SPECIAL_COLOR
                elif tool.startswith("pyrosm"):
                    color = PYROSM_COLOR
                else:
                    color = OTHER_COLOR
                ax.barh(y, value, color=color, alpha=1.0 if tag == "" else 0.5)
                ax.text(value, y, " " + fmt(value) + tag, va="center", ha="left",
                        fontsize=8, color="#333333")
            else:
                ax.text(0, y, " " + note, va="center", ha="left", fontsize=8, color="grey")
        if special:                                # set the not-comparable row off from the rest
            ax.axhline(0.5, color="#d9d9d9", lw=0.9, ls="--")
        ax.set_yticks([n - 1 - i for i in range(n)])
        ax.set_yticklabels([e[0] + ("*" if e[0] == SPECIAL_TOOL else "") for e in entries], fontsize=8)
        ax.set_ylim(-0.6, n - 0.5)                 # space below the last row so its note clears the x-axis
        ax.set_title(area, loc="left", fontsize=12, fontweight="bold")
        ax.set_xlabel(xlabel, fontsize=9)
        ax.grid(axis="y", visible=False)
        ax.tick_params(length=0)
        measured = [e[1] for e in entries if e[1] == e[1]]
        ax.set_xlim(0, (max(measured) if measured else 1) * 1.3)   # headroom for value labels + tags

    fig.suptitle(suptitle, fontsize=14, fontweight="bold", x=0.01, ha="left")
    bottom = 0.0
    if SPECIAL_TOOL in TOOL_ORDER:
        fig.text(0.01, 0.006, SPECIAL_NOTE, ha="left", va="bottom",
                 fontsize=8, color="grey", style="italic")
        bottom = 0.03
    fig.tight_layout(rect=[0, bottom, 1, 0.99])
    fig.savefig(f"{FIGURE_DIR}/{png}")
    plt.show()


plot_per_area("buildings", "seconds", "seconds (lower is better)", lambda v: f"{v:.0f}s",
              "Parsing buildings - speed", "buildings_time.png")
plot_per_area("buildings", "peak_mb", "peak memory, MB (lower is better)", lambda v: f"{v:,.0f} MB",
              "Parsing buildings - peak memory", "buildings_memory.png")
plot_per_area("roads", "seconds", "seconds (lower is better)", lambda v: f"{v:.0f}s",
              "Parsing the road network - speed", "network_time.png")
plot_per_area("roads", "peak_mb", "peak memory, MB (lower is better)", lambda v: f"{v:,.0f} MB",
              "Parsing the road network - peak memory", "network_memory.png")
../_images/b3c67c641d96eb23ab345e2f10a54fc5fca9e7e9a80b7ca4bd291f004676ab92.png ../_images/b0200a45c7f1c49fb01021fd672cdcab9e62557ae4cf33a5f3225fa49753c2cc.png ../_images/eda7b8ec221b852c4283f0784cbd03e5b55ae0aebc38f82624d6bb75534f5a66.png ../_images/807ebda15a3fb66e92901263dba995d6b53c01ca16bab00fff493a7b0259005c.png

Reading buildings with the same workload — pyrosm vs QuackOSM#

Time and peak memory side by side, one area per row. Each panel keeps its own scale, so the small areas stay readable next to the big ones — lower is better for both.

Hide code cell source

# Head-to-head: pyrosm (out-of-core) vs quackosm reading buildings, time and peak memory side by
# side, one row per area. Each panel keeps its own x-scale so the small areas are not dwarfed by
# the big ones (lower is better for both).
H2H_TASK = "buildings (geometry + key)"
PYROSM_H2H, QUACK_H2H = "pyrosm (out-of-core)", "quackosm"

h2h = (parsing_table[parsing_table["task"] == H2H_TASK]
       .drop_duplicates(subset=["area", "tool"], keep="last"))
h2h_areas = [a for a in area_order if a in set(h2h["area"])]


def _secs(v):
    return f"{v:.0f} s" if v >= 10 else f"{v:.1f} s"


def _gb(v):
    return f"{v/1000:.1f} GB" if v >= 1000 else f"{v/1000:.2f} GB"


METRICS = [("seconds", "Time — lower is better", _secs),
           ("peak_mb", "Peak memory — lower is better", _gb)]

fig, axes = plt.subplots(len(h2h_areas), 2, figsize=(11, 1.5 * len(h2h_areas)), squeeze=False)
for r, area in enumerate(h2h_areas):
    sub = h2h[h2h["area"] == area].set_index("tool")
    for c, (metric, header, fmt) in enumerate(METRICS):
        ax = axes[r, c]
        values = []
        for y, tool, color in ((1, PYROSM_H2H, PYROSM_COLOR), (0, QUACK_H2H, OTHER_COLOR)):
            row = sub.loc[tool] if tool in sub.index else None
            if row is not None and pd.notna(row[metric]) and not _failed(row):
                # A peak memory of a run that did not finish is faded and tagged, as above.
                value, tag = float(row[metric]), _incomplete_tag(row)
                values.append(value)
                ax.barh(y, value, color=color, height=0.62, alpha=1.0 if tag == "" else 0.5)
                ax.text(value, y, " " + fmt(value) + tag, va="center", ha="left", fontsize=9,
                        color="#333333")
            else:
                ax.text(0, y, " " + _status_note(row, area), va="center", ha="left", fontsize=9,
                        color="grey")
        ax.set_xlim(0, (max(values) if values else 1) * 1.32)
        ax.set_ylim(-0.6, 1.6)
        ax.set_yticks([1, 0])
        ax.set_yticklabels([])
        ax.set_xticklabels([])
        ax.grid(axis="y", visible=False)
        ax.tick_params(length=0)
        if r == 0:
            ax.set_title(header, loc="left", fontsize=12, fontweight="bold", pad=10)
    axes[r, 0].set_ylabel(area, rotation=0, ha="right", va="center", fontsize=11,
                          fontweight="bold", labelpad=14)

handles = [plt.Rectangle((0, 0), 1, 1, color=PYROSM_COLOR),
           plt.Rectangle((0, 0), 1, 1, color=OTHER_COLOR)]
fig.suptitle("Reading buildings — pyrosm vs quackosm", fontsize=15, fontweight="bold",
             x=0.5, ha="center", y=0.995)
fig.text(s="Identical workload: geometry + a single tag", fontsize=10, #fontweight="bold",
             x=0.5, ha="center", y=0.953)
fig.legend(handles, ["pyrosm (out-of-core)", "quackosm"], loc="upper center",
           bbox_to_anchor=(0.5, 0.95), ncol=2, frameon=False, fontsize=11)
fig.tight_layout(rect=[0.02, 0.02, 1, 0.93])
fig.savefig(f"{FIGURE_DIR}/head_to_head.png")
plt.show()
../_images/13d63afe1858ca3eccdbb908136a6af22a22f7ed72aac447f846f9726be72a91.png

Time to crop a country-level PBF into a smaller one#

Hide code cell source

# Crop times: horizontal bars, fastest at the top, with pyrosm highlighted.
if "crop_table" in globals() and not crop_table.empty:
    runs = crop_table[crop_table["status"] == "ok"].copy()
    # The serial (single-process) crop rows carry no parallelism label ("run"); show them
    # under the tool name. Without this the "run" column is a float (NaN) for those rows and
    # the categorical y-axis raises "TypeError: 'value' must be ... not a float".
    if "run" not in runs.columns:
        runs["run"] = runs["tool"]
    else:
        runs["run"] = runs["run"].fillna(runs["tool"])
    runs = runs.sort_values("seconds")

    fig, ax = plt.subplots(figsize=(9.5, 6))
    bars = ax.barh(runs["run"], runs["seconds"], color=bar_colors(runs["tool"]))
    ax.bar_label(bars, fmt="%.0fs", padding=4, fontsize=9.5, color="#333333")
    ax.invert_yaxis()   # fastest at the top
    ax.set_xlim(0, runs["seconds"].max() * 1.10)   # headroom for the bar labels
    ax.grid(axis="y", visible=False)
    ax.tick_params(length=0)
    ax.set_xlabel("seconds (lower is better)")
    ax.set_title("Cropping all of Finland to the Helsinki region (write .osm.pbf)",
                 loc="left", fontsize=14)

    fig.tight_layout()
    fig.savefig(f"{FIGURE_DIR}/crop_times.png")
    plt.show()
../_images/7c88784452765112cba5d8c221e2995953db374a14d3cef30637f79f72d8742e.png