1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#!/usr/bin/env python3
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import io
import json
import lzma
import os
import sys
from pathlib import Path
from timeit import timeit
from tabulate import tabulate
import orjson
os.sched_setaffinity(os.getpid(), {0, 1})
dirname = os.path.join(os.path.dirname(__file__), "..", "data")
def read_fixture_obj(filename):
path = Path(dirname, filename)
if path.suffix == ".xz":
contents = lzma.decompress(path.read_bytes())
else:
contents = path.read_bytes()
return orjson.loads(contents)
filename = sys.argv[1] if len(sys.argv) >= 1 else ""
data = read_fixture_obj(f"{filename}.json.xz")
headers = ("Library", "compact (ms)", "pretty (ms)", "vs. orjson")
LIBRARIES = ("orjson", "json")
output_in_kib_compact = len(orjson.dumps(data)) / 1024
output_in_kib_pretty = len(orjson.dumps(data, option=orjson.OPT_INDENT_2)) / 1024
# minimum 2s runtime for orjson compact
ITERATIONS = int(2 / (timeit(lambda: orjson.dumps(data), number=20) / 20))
print(
f"{output_in_kib_compact:,.0f}KiB compact, {output_in_kib_pretty:,.0f}KiB pretty, {ITERATIONS} iterations"
)
def per_iter_latency(val):
if val is None:
return None
return (val * 1000) / ITERATIONS
def test_correctness(serialized):
return orjson.loads(serialized) == data
table = []
for lib_name in LIBRARIES:
print(f"{lib_name}...")
if lib_name == "json":
time_compact = timeit(
lambda: json.dumps(data).encode("utf-8"),
number=ITERATIONS,
)
time_pretty = timeit(
lambda: json.dumps(data, indent=2).encode("utf-8"),
number=ITERATIONS,
)
correct = test_correctness(json.dumps(data, indent=2).encode("utf-8"))
elif lib_name == "orjson":
time_compact = timeit(lambda: orjson.dumps(data), number=ITERATIONS)
time_pretty = timeit(
lambda: orjson.dumps(data, None, orjson.OPT_INDENT_2),
number=ITERATIONS,
)
correct = test_correctness(orjson.dumps(data, None, orjson.OPT_INDENT_2))
orjson_time_pretty = per_iter_latency(time_pretty)
else:
raise NotImplementedError
time_compact = per_iter_latency(time_compact)
if not correct:
time_pretty = None
else:
time_pretty = per_iter_latency(time_pretty)
if lib_name == "orjson":
compared_to_orjson = 1
elif time_pretty:
compared_to_orjson = time_pretty / orjson_time_pretty
else:
compared_to_orjson = None
table.append(
(
lib_name,
f"{time_compact:,.2f}" if time_compact else "",
f"{time_pretty:,.2f}" if time_pretty else "",
f"{compared_to_orjson:,.1f}" if compared_to_orjson else "",
)
)
buf = io.StringIO()
buf.write(tabulate(table, headers, tablefmt="github"))
buf.write("\n")
print(buf.getvalue())
|