bench.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env lua
  2. -- Simple JSON benchmark.
  3. --
  4. -- Your Mileage May Vary.
  5. --
  6. -- Mark Pulford <[email protected]>
  7. require "common"
  8. require "socket"
  9. local json = require "cjson"
  10. function benchmark(tests, seconds, rep)
  11. local function bench(func, iter)
  12. -- collectgarbage("stop")
  13. collectgarbage("collect")
  14. local t = socket.gettime()
  15. for i = 1, iter do
  16. func(i)
  17. end
  18. t = socket.gettime() - t
  19. -- collectgarbage("restart")
  20. return (iter / t)
  21. end
  22. -- Roughly calculate the number of interations required
  23. -- to obtain a particular time period.
  24. local function calc_iter(func, seconds)
  25. local base_iter = 10
  26. local rate = (bench(func, base_iter) + bench(func, base_iter)) / 2
  27. return math.ceil(seconds * rate)
  28. end
  29. local test_results = {}
  30. for name, func in pairs(tests) do
  31. -- k(number), v(string)
  32. -- k(string), v(function)
  33. -- k(number), v(function)
  34. if type(func) == "string" then
  35. name = func
  36. func = _G[name]
  37. end
  38. local iter = calc_iter(func, seconds)
  39. local result = {}
  40. for i = 1, rep do
  41. result[i] = bench(func, iter)
  42. end
  43. table.sort(result)
  44. test_results[name] = result[rep]
  45. end
  46. return test_results
  47. end
  48. function bench_file(filename)
  49. local data_json = file_load(filename)
  50. local data_obj = json.decode(data_json)
  51. local function test_encode ()
  52. json.encode(data_obj)
  53. end
  54. local function test_decode ()
  55. json.decode(data_json)
  56. end
  57. local tests = {
  58. encode = test_encode,
  59. decode = test_decode
  60. }
  61. return benchmark(tests, 0.1, 5)
  62. end
  63. cjson.encode_keep_buffer(true)
  64. for i = 1, #arg do
  65. local results = bench_file(arg[i])
  66. for k, v in pairs(results) do
  67. print(string.format("%s: %s: %d", arg[i], k, v))
  68. end
  69. end
  70. -- vi:ai et sw=4 ts=4: