|
| 1 | +import os |
| 2 | + |
| 3 | +# set before importing `msgpack` |
| 4 | +os.environ["MSGPACK_PUREPYTHON"] = "1" |
| 5 | + |
| 6 | +from msgpack_stream import unpack, unpack_stream |
| 7 | +from mmap import mmap, ACCESS_READ |
| 8 | +import argparse |
| 9 | +import timeit |
| 10 | + |
| 11 | +from msgpack import unpackb |
| 12 | + |
| 13 | + |
| 14 | +FILE = "scripts/obj.msgpack" |
| 15 | + |
| 16 | + |
| 17 | +def main(mapped): |
| 18 | + with open(FILE, "rb", buffering=0) as fd: |
| 19 | + if mapped: |
| 20 | + with mmap(fd.fileno(), 0, access=ACCESS_READ) as mm: |
| 21 | + return unpack(mm.read()) |
| 22 | + else: |
| 23 | + return unpack(fd.read()) |
| 24 | + |
| 25 | + |
| 26 | +def stream(mapped): |
| 27 | + with open(FILE, "rb", buffering=0) as fd: |
| 28 | + if mapped: |
| 29 | + with mmap(fd.fileno(), 0, access=ACCESS_READ) as mm: |
| 30 | + return unpack_stream(mm) |
| 31 | + else: |
| 32 | + return unpack_stream(fd) |
| 33 | + |
| 34 | + |
| 35 | +def other(mapped): |
| 36 | + with open(FILE, "rb", buffering=0) as fd: |
| 37 | + if mapped: |
| 38 | + with mmap(fd.fileno(), 0, access=ACCESS_READ) as mm: |
| 39 | + return unpackb(mm.read(), strict_map_key=False) |
| 40 | + else: |
| 41 | + return unpackb(fd.read(), strict_map_key=False) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + _globals = { |
| 46 | + "main": main, |
| 47 | + "stream": stream, |
| 48 | + "other": other, |
| 49 | + } |
| 50 | + parser = argparse.ArgumentParser() |
| 51 | + parser.add_argument("-n", "--number", type=int, default=25, help="Number of runs") |
| 52 | + args = parser.parse_args() |
| 53 | + |
| 54 | + t_main = timeit.timeit("main(True)", number=args.number, globals=_globals) |
| 55 | + # this needs to be mmap for good performance |
| 56 | + t_stream = timeit.timeit("stream(True)", number=args.number, globals=_globals) |
| 57 | + t_other = timeit.timeit("other(True)", number=args.number, globals=_globals) |
| 58 | + |
| 59 | + print(f"main: {t_main:.6f}s total, {t_main / args.number:.6f}s per call") |
| 60 | + print(f"stream: {t_stream:.6f}s total, {t_stream / args.number:.6f}s per call") |
| 61 | + print(f"other: {t_other:.6f}s total, {t_other / args.number:.6f}s per call") |
0 commit comments