diff --git a/Makefile b/Makefile index e5c3051a..a19a7a3c 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ uninstall: .PHONY: bench bench: - @dune build bench/bench.exe + @dune build @bench --force .PHONY: clean clean: @@ -25,3 +25,4 @@ clean: .PHONY: test test: @dune runtest --force + diff --git a/bench/README.md b/bench/README.md new file mode 100644 index 00000000..25f45723 --- /dev/null +++ b/bench/README.md @@ -0,0 +1,20 @@ +Benchmark for Yojson +==================== + +These benchmarks require `Core_bench` which is not a dependency of Yojson, +because it is not part of the regular installation/testing flow. This is solely +meant for developers that are worried about performance changes in Yojson. + +This is also why it is deemed appropriate to depend on a benchmarking library +with this many dependencies: we rather spend time writing benchmarks than to +build a benchmarking library if a perfectly good one already exists in OCaml. + +Install +------- + +`opam install core_benchmark` + +Running the benchmark +--------------------- + +`make bench` in the top level directory. diff --git a/sample.json b/bench/bench.json similarity index 100% rename from sample.json rename to bench/bench.json diff --git a/bench/bench.ml b/bench/bench.ml index 05ee8989..1d365390 100644 --- a/bench/bench.ml +++ b/bench/bench.ml @@ -1,33 +1,18 @@ +open Core +open Core_bench + let data = - let l = ref [] in - try - while true do - l := input_line stdin :: !l - done; - assert false - with End_of_file -> String.concat "\n" (List.rev !l) + In_channel.read_all "bench.json" let yojson_data = Yojson.Safe.from_string data -let n = 10_000 - -let yojson_rd_loop () = - for i = 1 to n do - ignore (Yojson.Safe.from_string data) - done - -let yojson_wr_loop () = - for i = 1 to n do - ignore (Yojson.Safe.to_string yojson_data) - done - -let time msg f = - let t1 = Unix.gettimeofday () in - f (); - let t2 = Unix.gettimeofday () in - Printf.printf "%s: %.3f\n%!" msg (t2 -. t1) +let main () = + Command.run (Bench.make_command [ + Bench.Test.create ~name:"JSON reading" (fun () -> + ignore (Yojson.Safe.from_string data)); + Bench.Test.create ~name:"JSON writing" (fun () -> + ignore (Yojson.Safe.to_string yojson_data)); + ]) let () = - time "rd yojson" yojson_rd_loop; - - time "wr yojson" yojson_wr_loop; + main () diff --git a/bench/dune b/bench/dune index 3787f61c..8c17e857 100644 --- a/bench/dune +++ b/bench/dune @@ -1,8 +1,9 @@ (executable (name bench) (flags (-safe-string)) - (libraries yojson unix)) + (libraries yojson core_bench core)) (alias (name bench) + (deps bench.json) (action (run ./bench.exe)))