| 1 |
"""Measure the filelock performance matrix and print it as a report. |
| 2 |
|
| 3 |
The numbers establish a baseline rather than gate a build: run it before and after a change to compare medians and tail |
| 4 |
latency, the way :issue:`642` describes. Run with ``python tasks/benchmark.py`` or ``tox -e bench``. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import asyncio |
| 10 |
import os |
| 11 |
import platform |
| 12 |
import statistics |
| 13 |
import sys |
| 14 |
import time |
| 15 |
from contextlib import suppress |
| 16 |
from dataclasses import dataclass |
| 17 |
from multiprocessing import Event, Process |
| 18 |
from pathlib import Path |
| 19 |
from tempfile import TemporaryDirectory |
| 20 |
from typing import TYPE_CHECKING, Final |
| 21 |
|
| 22 |
import filelock |
| 23 |
from filelock import AsyncFileLock, FileLock, SoftFileLease, SoftFileLock, StrictSoftFileLock |
| 24 |
|
| 25 |
if TYPE_CHECKING: |
| 26 |
from collections.abc import Callable, Iterator |
| 27 |
from multiprocessing.synchronize import Event as EventType |
| 28 |
|
| 29 |
_ITERATIONS: Final[int] = 200 |
| 30 |
_WARMUP: Final[int] = 20 |
| 31 |
_CONTENTION_PROCESSES: Final[int] = 8 |
| 32 |
_CONTENTION_ACQUISITIONS: Final[int] = 500 |
| 33 |
|
| 34 |
|
| 35 |
@dataclass(frozen=True) |
| 36 |
class Sample: |
| 37 |
"""One measured metric, in the unit named by ``unit``.""" |
| 38 |
|
| 39 |
name: str |
| 40 |
median: float |
| 41 |
p95: float |
| 42 |
unit: str |
| 43 |
|
| 44 |
|
| 45 |
def main() -> None: |
| 46 |
print(_environment()) |
| 47 |
samples: list[Sample] = [] |
| 48 |
with TemporaryDirectory(prefix="filelock-bench-") as directory: |
| 49 |
root = Path(directory) |
| 50 |
samples += _construction(root) |
| 51 |
samples += _uncontended(root) |
| 52 |
samples.append(_timeout_cpu(root)) |
| 53 |
samples.append(_descriptor_growth(root)) |
| 54 |
samples += _cancellation_latency(root) |
| 55 |
samples += _contention(root) |
| 56 |
_report(samples) |
| 57 |
|
| 58 |
|
| 59 |
def _environment() -> str: |
| 60 |
gil = getattr(sys, "_is_gil_enabled", lambda: True)() |
| 61 |
build = "gil" if gil else "free-threaded" |
| 62 |
return ( |
| 63 |
f"filelock {filelock.__version__} | {platform.python_implementation()} {platform.python_version()} ({build}) | " |
| 64 |
f"{platform.system()} {platform.machine()} | {os.cpu_count()} cpus" |
| 65 |
) |
| 66 |
|
| 67 |
|
| 68 |
def _backends(root: Path) -> Iterator[tuple[str, Callable[[], filelock.BaseFileLock]]]: |
| 69 |
# Each entry builds a fresh lock on its own path so no two cases contend. ReadWriteLock is soft-optional, so it is |
| 70 |
# measured separately where it applies rather than through this exclusive-lock set. |
| 71 |
yield "FileLock", lambda: FileLock(str(root / "file.lock")) |
| 72 |
yield "SoftFileLock", lambda: SoftFileLock(str(root / "soft.lock")) |
| 73 |
yield "StrictSoftFileLock", lambda: StrictSoftFileLock(str(root / "strict.lock")) |
| 74 |
yield "SoftFileLease", lambda: SoftFileLease(str(root / "lease.lock"), lease_duration=30) |
| 75 |
|
| 76 |
|
| 77 |
def _construction(root: Path) -> list[Sample]: |
| 78 |
return [_timed(f"construct {name}", build, unit="us", scale=1e6) for name, build in _backends(root)] |
| 79 |
|
| 80 |
|
| 81 |
def _uncontended(root: Path) -> list[Sample]: |
| 82 |
samples: list[Sample] = [] |
| 83 |
for name, build in _backends(root): |
| 84 |
lock = build() |
| 85 |
|
| 86 |
def acquire_release(held: filelock.BaseFileLock = lock) -> None: |
| 87 |
held.acquire() |
| 88 |
held.release() |
| 89 |
|
| 90 |
samples.append(_timed(f"acquire+release {name}", acquire_release, unit="us", scale=1e6)) |
| 91 |
return samples |
| 92 |
|
| 93 |
|
| 94 |
def _timeout_cpu(root: Path) -> Sample: |
| 95 |
# A contended acquire with a zero poll interval should spin on the clock, not the CPU. Hold the lock, time out a |
| 96 |
# second acquirer, and report the CPU time the wait burned; a busy loop would show wall-sized CPU here. |
| 97 |
holder = FileLock(str(root / "timeout.lock")) |
| 98 |
holder.acquire() |
| 99 |
waiter = FileLock(str(root / "timeout.lock")) |
| 100 |
try: |
| 101 |
started = time.process_time() |
| 102 |
with suppress(filelock.Timeout): |
| 103 |
waiter.acquire(timeout=0.25, poll_interval=0.0) |
| 104 |
cpu = time.process_time() - started |
| 105 |
finally: |
| 106 |
holder.release() |
| 107 |
return Sample("timeout cpu (0.25s wall, poll=0)", cpu * 1e3, cpu * 1e3, "ms cpu") |
| 108 |
|
| 109 |
|
| 110 |
def _descriptor_growth(root: Path) -> Sample: |
| 111 |
# Acquire and release many times; a descriptor leak would show as a rising open-descriptor count. |
| 112 |
lock = FileLock(str(root / "fd.lock")) |
| 113 |
before = _open_descriptors() |
| 114 |
for _ in range(100): |
| 115 |
lock.acquire() |
| 116 |
lock.release() |
| 117 |
grew = _open_descriptors() - before |
| 118 |
return Sample("descriptor growth over 100 cycles", float(grew), float(grew), "fds") |
| 119 |
|
| 120 |
|
| 121 |
def _cancellation_latency(root: Path) -> list[Sample]: |
| 122 |
# Hold the lock from another process so the async waiter blocks on the OS lock rather than on a peer instance in the |
| 123 |
# same task, which the deadlock guard would refuse. Then time canceling the awaiting task to the acquire unwinding. |
| 124 |
path = str(root / "cancel.lock") |
| 125 |
acquired, release = Event(), Event() |
| 126 |
holder = Process(target=_hold_until, args=(path, acquired, release)) |
| 127 |
holder.start() |
| 128 |
|
| 129 |
async def measure() -> float: |
| 130 |
waiter = AsyncFileLock(path) |
| 131 |
task = asyncio.ensure_future(waiter.acquire(poll_interval=0.01)) |
| 132 |
await asyncio.sleep(0.02) |
| 133 |
started = time.perf_counter() |
| 134 |
task.cancel() |
| 135 |
with suppress(asyncio.CancelledError): |
| 136 |
await task |
| 137 |
return time.perf_counter() - started |
| 138 |
|
| 139 |
try: |
| 140 |
acquired.wait(timeout=5) |
| 141 |
latencies = [asyncio.run(measure()) for _ in range(20)] |
| 142 |
finally: |
| 143 |
release.set() |
| 144 |
holder.join(timeout=5) |
| 145 |
return [ |
| 146 |
Sample( |
| 147 |
"async acquire cancellation latency", |
| 148 |
statistics.median(latencies) * 1e3, |
| 149 |
_percentile(latencies, 95) * 1e3, |
| 150 |
"ms", |
| 151 |
) |
| 152 |
] |
| 153 |
|
| 154 |
|
| 155 |
def _hold_until(path: str, acquired: EventType, release: EventType) -> None: |
| 156 |
lock = FileLock(path) |
| 157 |
lock.acquire() |
| 158 |
acquired.set() |
| 159 |
release.wait(timeout=30) |
| 160 |
lock.release() |
| 161 |
|
| 162 |
|
| 163 |
def _contention(root: Path) -> list[Sample]: |
| 164 |
samples: list[Sample] = [] |
| 165 |
for name, path in (("FileLock", root / "c-file.lock"), ("StrictSoftFileLock", root / "c-strict.lock")): |
| 166 |
started = time.perf_counter() |
| 167 |
workers = [Process(target=_hammer, args=(name, str(path))) for _ in range(_CONTENTION_PROCESSES)] |
| 168 |
for worker in workers: |
| 169 |
worker.start() |
| 170 |
for worker in workers: |
| 171 |
worker.join() |
| 172 |
elapsed = time.perf_counter() - started |
| 173 |
total = _CONTENTION_PROCESSES * _CONTENTION_ACQUISITIONS |
| 174 |
per = elapsed * 1e3 / total |
| 175 |
samples.append(Sample(f"contention {name} ({total} acquisitions)", per, per, "ms/acq")) |
| 176 |
return samples |
| 177 |
|
| 178 |
|
| 179 |
def _hammer(backend: str, path: str) -> None: |
| 180 |
lock = FileLock(path) if backend == "FileLock" else StrictSoftFileLock(path) |
| 181 |
for _ in range(_CONTENTION_ACQUISITIONS): |
| 182 |
lock.acquire() |
| 183 |
lock.release() |
| 184 |
|
| 185 |
|
| 186 |
def _timed(name: str, run: Callable[[], object], *, unit: str, scale: float) -> Sample: |
| 187 |
for _ in range(_WARMUP): |
| 188 |
run() |
| 189 |
durations = [_one(run) for _ in range(_ITERATIONS)] |
| 190 |
return Sample(name, statistics.median(durations) * scale, _percentile(durations, 95) * scale, unit) |
| 191 |
|
| 192 |
|
| 193 |
def _one(run: Callable[[], object]) -> float: |
| 194 |
started = time.perf_counter() |
| 195 |
run() |
| 196 |
return time.perf_counter() - started |
| 197 |
|
| 198 |
|
| 199 |
def _percentile(values: list[float], percentile: int) -> float: |
| 200 |
ordered = sorted(values) |
| 201 |
index = min(len(ordered) - 1, round(percentile / 100 * len(ordered))) |
| 202 |
return ordered[index] |
| 203 |
|
| 204 |
|
| 205 |
def _open_descriptors() -> int: |
| 206 |
for directory in ("/proc/self/fd", "/dev/fd"): |
| 207 |
with suppress(OSError): |
| 208 |
return sum(1 for _ in Path(directory).iterdir()) |
| 209 |
return 0 # pragma: no cover # neither procfs nor /dev/fd exists on this platform |
| 210 |
|
| 211 |
|
| 212 |
def _report(samples: list[Sample]) -> None: |
| 213 |
width = max(len(sample.name) for sample in samples) |
| 214 |
print(f"\n{'metric':<{width}} {'median':>12} {'p95':>12} unit") |
| 215 |
print("-" * (width + 34)) |
| 216 |
for sample in samples: |
| 217 |
print(f"{sample.name:<{width}} {sample.median:>12.3f} {sample.p95:>12.3f} {sample.unit}") |
| 218 |
|
| 219 |
|
| 220 |
if __name__ == "__main__": |
| 221 |
main() |