diff options
Diffstat (limited to '')
| -rw-r--r-- | tests/common.lua | 79 |
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 @@ | |||
| 1 | require "cjson" | ||
| 2 | require "posix" | ||
| 3 | |||
| 4 | function 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 | |||
| 29 | end | ||
| 30 | |||
| 31 | function 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 | ||
| 40 | end | ||
| 41 | |||
| 42 | function gettimeofday() | ||
| 43 | local tv_sec, tv_usec = posix.gettimeofday() | ||
| 44 | |||
| 45 | return tv_sec + tv_usec / 1000000 | ||
| 46 | end | ||
| 47 | |||
| 48 | function 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 | ||
| 77 | end | ||
| 78 | |||
| 79 | -- vi:ai et sw=4 ts=4: | ||
