import timeit import statistics WITH_FNAME = """ from gzip import GzipFile, decompress, _read_gzip_header import io fileobj = io.BytesIO() g = GzipFile(fileobj=fileobj, mode='wb', filename='compressable_file') g.write(b'') g.close() data=fileobj.getvalue() """ WITH_NO_FLAGS = """ import io from gzip import compress, _read_gzip_header data = gzip.compress(b'', mtime=0) """ ALLFLAGHEADER = ( b'\x1f\x8b\x08\x1f\x00\x00\x00\x00\x00\xff' b'\x05\x00' # Xlen = 5 b'extra' b'name\x00' b'comment\x00') WITH_ALL_FLAGS = f""" import zlib from gzip import _read_gzip_header import io header = {ALLFLAGHEADER} hcrc = zlib.crc32(header) & 0xffff compressed = zlib.compress(b"", wbits=-15) trailer = bytes(8) # No length, and checksum is zero as well data = header + hcrc.to_bytes(2, "little") + compressed + trailer """ def benchmark(name, setup, loops=5000, runs=100): print(f"{name}") results = [timeit.timeit("_read_gzip_header(io.BytesIO(data))", setup, number=loops) for _ in range(runs)] # Calculate microseconds results = [(result / loops) * 1_000_000 for result in results] print(f"average: {round(statistics.mean(results), 2)}, " f"range: {round(min(results), 2)}-{round(max(results),2)} " f"stdev: {round(statistics.stdev(results),2)}") if __name__ == "__main__": benchmark("with_fname", WITH_FNAME) benchmark("with_noflags", WITH_FNAME) benchmark("All flags (incl FHCRC)", WITH_ALL_FLAGS)