Benchmark Disk Write Speed in Python with tempfile

Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Python code

24 lines
Python 3.9+
import os
import tempfile
import time

def benchmark_write(size_mb=50):
    size_bytes = size_mb * 1024 * 1024
    chunk = b'x' * 1024 * 1024  # 1 MB chunk

    with tempfile.NamedTemporaryFile(delete=True) as tmp:
        start = time.perf_counter()
        written = 0
        while written < size_bytes:
            tmp.write(chunk[:min(len(chunk), size_bytes - written)])
            written += len(chunk)
        tmp.flush()
        os.fsync(tmp.fileno())
        elapsed = time.perf_counter() - start

    speed_mbs = size_mb / elapsed
    print(f"Wrote {size_mb} MB in {elapsed:.3f}s — {speed_mbs:.2f} MB/s")
    return speed_mbs

if __name__ == "__main__":
    benchmark_write(50)

Output

stdout
Wrote 50 MB in 0.145s — 344.83 MB/s

How it works

This works because tempfile.NamedTemporaryFile creates a real file on the filesystem, so writes go through the OS page cache and disk driver exactly like production I/O. Writing in fixed 1MB chunks avoids per-write overhead dominating the measurement. The flush() call pushes buffered data to the OS, and os.fsync() forces it all the way to physical disk — without these, the benchmark only measures userspace memory speed. Timing with time.perf_counter gives high-resolution wall-clock time, and the throughput formula converts elapsed time into MB/s.

Common mistakes

  • Forgetting `os.fsync()` — results then measure memory writes, not disk throughput
  • Writing in tiny chunks — per-write syscall overhead skews results downward
  • Using `delete=False` and leaving temp files on disk after the benchmark
  • Ignoring page cache warm-up on repeated runs

Variations

  1. Use `pathlib.Path` and `open()` with a fixed filename to benchmark a specific target disk
  2. Measure read speed separately with `f.read(chunk)` in the same loop

Real-world use cases

  • Validating SSD vs HDD performance before choosing storage for an application.
  • CI pipeline speed checks that fail if write throughput drops below a threshold.
  • Comparing filesystem performance for different mount options in production environments.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.