|
| 1 | +#!/usr/env/bin python |
| 2 | +""" |
| 3 | +Benchmark the performance of jsonschema. |
| 4 | +
|
| 5 | +Example benchmark: |
| 6 | +
|
| 7 | + wget http://swagger.io/v2/schema.json |
| 8 | + wget http://petstore.swagger.io/v2/swagger.json |
| 9 | + python bench.py -r 5 schema.json swagger.json |
| 10 | +
|
| 11 | +""" |
| 12 | +from __future__ import print_function |
| 13 | +import argparse |
| 14 | +import cProfile |
| 15 | +import json |
| 16 | +import time |
| 17 | + |
| 18 | +import jsonschema |
| 19 | + |
| 20 | + |
| 21 | +def parse_args(): |
| 22 | + parser = argparse.ArgumentParser() |
| 23 | + parser.add_argument('schema', help="path to a schema used to benchmark") |
| 24 | + parser.add_argument('document', help="document to validate with schema") |
| 25 | + parser.add_argument('-r', '--repeat', type=int, help="number of iterations") |
| 26 | + parser.add_argument('--profile', |
| 27 | + help="Enable profiling, write profile to this filepath") |
| 28 | + return parser.parse_args() |
| 29 | + |
| 30 | + |
| 31 | +def run(filename, schema, document): |
| 32 | + resolver = jsonschema.RefResolver( |
| 33 | + 'file://{0}'.format(filename), |
| 34 | + schema, |
| 35 | + store={schema['id']: schema}) |
| 36 | + jsonschema.validate(document, schema, resolver=resolver) |
| 37 | + |
| 38 | + |
| 39 | +def format_time(time_): |
| 40 | + return "%.3fms" % (time_ * 1000) |
| 41 | + |
| 42 | + |
| 43 | +def run_timeit(schema_filename, document_filename, repeat, profile): |
| 44 | + with open(schema_filename) as schema_file: |
| 45 | + schema = json.load(schema_file) |
| 46 | + |
| 47 | + with open(document_filename) as fh: |
| 48 | + document = json.load(fh) |
| 49 | + |
| 50 | + if profile: |
| 51 | + profiler = cProfile.Profile() |
| 52 | + profiler.enable() |
| 53 | + |
| 54 | + times = [] |
| 55 | + for _ in range(repeat): |
| 56 | + start_time = time.time() |
| 57 | + run(schema_filename, schema, document) |
| 58 | + times.append(time.time() - start_time) |
| 59 | + |
| 60 | + if profile: |
| 61 | + profiler.disable() |
| 62 | + profiler.dump_stats(profile) |
| 63 | + |
| 64 | + print(", ".join(map(format_time, sorted(times)))) |
| 65 | + print("Mean: {0}".format(format_time(sum(times) / repeat))) |
| 66 | + |
| 67 | + |
| 68 | +def main(): |
| 69 | + args = parse_args() |
| 70 | + run_timeit(args.schema, args.document, args.repeat, args.profile) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
0 commit comments