diff options
Diffstat (limited to 'tests/bench.lua')
-rwxr-xr-x | tests/bench.lua | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/tests/bench.lua b/tests/bench.lua new file mode 100755 index 0000000..2b5177b --- /dev/null +++ b/tests/bench.lua | |||
@@ -0,0 +1,83 @@ | |||
1 | #!/usr/bin/env lua | ||
2 | |||
3 | -- Simple JSON benchmark. | ||
4 | -- | ||
5 | -- Your Mileage May Vary. | ||
6 | -- | ||
7 | -- Mark Pulford <mark@kyne.com.au> | ||
8 | |||
9 | require "socket" | ||
10 | local json = require "cjson" | ||
11 | local misc = require "cjson-misc" | ||
12 | |||
13 | function benchmark(tests, seconds, rep) | ||
14 | local function bench(func, iter) | ||
15 | -- collectgarbage("stop") | ||
16 | collectgarbage("collect") | ||
17 | local t = socket.gettime() | ||
18 | for i = 1, iter do | ||
19 | func(i) | ||
20 | end | ||
21 | t = socket.gettime() - t | ||
22 | -- collectgarbage("restart") | ||
23 | return (iter / t) | ||
24 | end | ||
25 | |||
26 | -- Roughly calculate the number of interations required | ||
27 | -- to obtain a particular time period. | ||
28 | local function calc_iter(func, seconds) | ||
29 | local base_iter = 10 | ||
30 | local rate = (bench(func, base_iter) + bench(func, base_iter)) / 2 | ||
31 | return math.ceil(seconds * rate) | ||
32 | end | ||
33 | |||
34 | local test_results = {} | ||
35 | for name, func in pairs(tests) do | ||
36 | -- k(number), v(string) | ||
37 | -- k(string), v(function) | ||
38 | -- k(number), v(function) | ||
39 | if type(func) == "string" then | ||
40 | name = func | ||
41 | func = _G[name] | ||
42 | end | ||
43 | local iter = calc_iter(func, seconds) | ||
44 | local result = {} | ||
45 | for i = 1, rep do | ||
46 | result[i] = bench(func, iter) | ||
47 | end | ||
48 | table.sort(result) | ||
49 | test_results[name] = result[rep] | ||
50 | end | ||
51 | |||
52 | return test_results | ||
53 | end | ||
54 | |||
55 | function bench_file(filename) | ||
56 | local data_json = misc.file_load(filename) | ||
57 | local data_obj = json.decode(data_json) | ||
58 | |||
59 | local function test_encode () | ||
60 | json.encode(data_obj) | ||
61 | end | ||
62 | local function test_decode () | ||
63 | json.decode(data_json) | ||
64 | end | ||
65 | |||
66 | local tests = { | ||
67 | encode = test_encode, | ||
68 | decode = test_decode | ||
69 | } | ||
70 | |||
71 | return benchmark(tests, 0.1, 5) | ||
72 | end | ||
73 | |||
74 | json.encode_keep_buffer(true) | ||
75 | |||
76 | for i = 1, #arg do | ||
77 | local results = bench_file(arg[i]) | ||
78 | for k, v in pairs(results) do | ||
79 | print(string.format("%s: %s: %d", arg[i], k, v)) | ||
80 | end | ||
81 | end | ||
82 | |||
83 | -- vi:ai et sw=4 ts=4: | ||