perf(scan): read files in 256 KiB chunks instead of 8 KiB

Hashing runs in threads via asyncio.to_thread, and hashlib/zlib release
the GIL per chunk. At 8 KiB the threads hand the GIL back so often that
concurrent scans contend rather than overlap, which capped scan
concurrency and made high worker counts actively harmful.

Hashing 1.96 GiB of real ROM files at 8 workers goes from 154 MiB/s to
666 MiB/s (4.3x). Single-worker throughput is unchanged (108 vs 114
MiB/s), so this is not read-syscall overhead; it only bites under
concurrency. 256 KiB is the knee, 1 MiB measured no better.

The chunk bounds a streaming read, so peak memory is one chunk per
in-flight file, a few MiB at any realistic worker count.

Digests are unaffected: all 67 files in the test library produce
byte-identical crc/md5/sha1 at 8 KiB, 64 KiB, 256 KiB and 1 MiB.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Spinnich
2026-09-07 17:55:19 +00:00
parent 0ea9d3d948
commit abade695c7

View File

@@ -61,7 +61,10 @@ CHD_V5_SHA1_LENGTH: Final = 20 # SHA1 is 20 bytes
CHD_V5_VERSION: Final = 5 # CHD v5 identifier
CHD_MIME_TYPE: Final = "application/x-mame-chd"
FILE_READ_CHUNK_SIZE = 1024 * 8
# Hashing runs in threads, and hashlib/zlib release the GIL per chunk. Small
# chunks hand the GIL back so often that concurrent scans contend instead of
# overlapping; 256 KiB is where that stops costing throughput.
FILE_READ_CHUNK_SIZE = 1024 * 256
_MIME_DETECTOR = magic.Magic(mime=True)
_MIME_DETECTOR_LOCK = threading.Lock()