aboutsummaryrefslogtreecommitdiff
path: root/tests/common.lua
diff options
context:
space:
mode:
authorMark Pulford <mark@kyne.com.au>2011-05-03 23:04:22 +0930
committerMark Pulford <mark@kyne.com.au>2011-05-03 23:04:22 +0930
commit4146070e69475d5eedcf7a9e3d990e511f46ec7a (patch)
tree5e6bfa66ee9a1fc4ac4125f349c55a3d7c551e35 /tests/common.lua
parentce3a769dbdd13571b5b761d933e17e8fe5771739 (diff)
downloadlua-cjson-4146070e69475d5eedcf7a9e3d990e511f46ec7a.tar.gz
lua-cjson-4146070e69475d5eedcf7a9e3d990e511f46ec7a.tar.bz2
lua-cjson-4146070e69475d5eedcf7a9e3d990e511f46ec7a.zip
Add basic JSON tests and benchmark
Diffstat (limited to 'tests/common.lua')
-rw-r--r--tests/common.lua79
1 files changed, 79 insertions, 0 deletions
diff --git a/tests/common.lua b/tests/common.lua
new file mode 100644
index 0000000..e935032
--- /dev/null
+++ b/tests/common.lua
@@ -0,0 +1,79 @@
1require "cjson"
2require "posix"
3
4function dump_value(value, indent)
5 if indent == nil then
6 indent = ""
7 end
8
9 if value == cjson.null then
10 value = "<cjson.null>"
11 end
12
13 if type(value) == "string" or type(value) == "number" or
14 type(value) == "boolean" then
15 print(indent .. tostring(value))
16 elseif type(value) == "table" then
17 local count = 0
18 for k, v in pairs(value) do
19 dump_value(v, indent .. k .. ": ")
20 count = count + 1
21 end
22 if count == 0 then
23 print(indent .. ": <empty>")
24 end
25 else
26 print(indent .. "<" .. type(value) .. ">")
27 end
28
29end
30
31function file_load(filename)
32 local file, err = io.open(filename)
33 if file == nil then
34 error("Unable to read " .. filename)
35 end
36 local data = file:read("*a")
37 file:close()
38
39 return data
40end
41
42function gettimeofday()
43 local tv_sec, tv_usec = posix.gettimeofday()
44
45 return tv_sec + tv_usec / 1000000
46end
47
48function benchmark(tests, iter, rep)
49 local function bench(func, iter)
50 collectgarbage("collect")
51 local t = gettimeofday()
52 for i = 1, iter do
53 func(i)
54 end
55 t = gettimeofday() - t
56 return (iter / t)
57 end
58
59 local test_results = {}
60 for name, func in pairs(tests) do
61 -- k(number), v(string)
62 -- k(string), v(function)
63 -- k(number), v(function)
64 if type(func) == "string" then
65 name = func
66 func = _G[name]
67 end
68 local result = {}
69 for i = 1, rep do
70 result[i] = bench(func, iter)
71 end
72 table.sort(result)
73 test_results[name] = result[rep]
74 end
75
76 return test_results
77end
78
79-- vi:ai et sw=4 ts=4: