|
| 1 | +""" |
| 2 | + Speed benchmark for saving/loading numpy arrays using various compression codecs |
| 3 | +""" |
| 4 | +import jdata as jd |
| 5 | +import numpy as np |
| 6 | +import time |
| 7 | +import os |
| 8 | + |
| 9 | +print("jdata version:" + jd.__version__) |
| 10 | + |
| 11 | +codecs = [ |
| 12 | + "npy", |
| 13 | + "npz", |
| 14 | + "bjd", |
| 15 | + "zlib", |
| 16 | + "lzma", |
| 17 | + "lz4", |
| 18 | + "blosc2blosclz", |
| 19 | + "blosc2lz4", |
| 20 | + "blosc2lz4hc", |
| 21 | + "blosc2zlib", |
| 22 | + "blosc2zstd", |
| 23 | +] |
| 24 | +nthread = 8 |
| 25 | + |
| 26 | + |
| 27 | +def benchmark(codec, x): |
| 28 | + t0 = time.time() |
| 29 | + ext = suffix |
| 30 | + if codec == "npy": |
| 31 | + ext = "." + codec |
| 32 | + np.save("matrix_" + codec + ext, x) |
| 33 | + elif codec == "npz": |
| 34 | + ext = "." + codec |
| 35 | + np.savez_compressed("matrix_" + codec + ext, x) |
| 36 | + elif codec == "bjd": |
| 37 | + ext = "." + codec |
| 38 | + jd.save(x, "matrix_" + codec + ext, {"encode": False}) |
| 39 | + else: |
| 40 | + jd.save(x, "matrix_" + codec + ext, {"compression": codec, "nthread": nthread}) |
| 41 | + dt = time.time() - t0 # saving time |
| 42 | + res = {"codec": codec, "save": dt} |
| 43 | + if codec == "npy": |
| 44 | + y = np.load("matrix_" + codec + ext) |
| 45 | + elif codec == "npz": |
| 46 | + y = np.load("matrix_" + codec + ext)["arr_0"] |
| 47 | + else: |
| 48 | + y = jd.load("matrix_" + codec + ext, {"nthread": nthread}) # loading |
| 49 | + res["sum"] = y.sum() |
| 50 | + res["load"] = time.time() - t0 - dt # loading time |
| 51 | + res["size"] = os.path.getsize("matrix_" + codec + ext) |
| 52 | + print(res) |
| 53 | + return res |
| 54 | + |
| 55 | + |
| 56 | +## a highly compressible matrix |
| 57 | +x = np.eye(10000) |
| 58 | + |
| 59 | +## a less compressible random matrix |
| 60 | +# np.random.seed(0) |
| 61 | +# x = np.random.rand(2000,2000) |
| 62 | + |
| 63 | +print("\n- Testing binary JSON (BJData) files (.jdb) ...") |
| 64 | + |
| 65 | +suffix = ".jdb" |
| 66 | +res = list(map(benchmark, codecs, [x] * len(codecs))) |
| 67 | +# print(np.array(res)) |
| 68 | + |
| 69 | +print("\n- Testing text-based JSON files (.jdt) ...") |
| 70 | + |
| 71 | +suffix = ".jdt" |
| 72 | +res = list(map(benchmark, codecs, [x] * len(codecs))) |
| 73 | +# print(np.array(res)) |
0 commit comments