|
| 1 | +local util = require('render-markdown.util') |
| 2 | + |
| 3 | +---@class render.md.OutputResultStat |
| 4 | +---@field n integer |
| 5 | +---@field min number |
| 6 | +---@field max number |
| 7 | +---@field sum number |
| 8 | +---@field mean number |
| 9 | + |
| 10 | +---@class render.md.OutputStat |
| 11 | +---@field path string |
| 12 | +---@field size number |
| 13 | +---@field results table<string, render.md.OutputResultStat> |
| 14 | + |
| 15 | +---buffer -> result_state -> times |
| 16 | +---@type table<integer, table<string, number[]>> |
| 17 | +local stats = {} |
| 18 | + |
| 19 | +---@class render.md.Profiler |
| 20 | +local M = {} |
| 21 | + |
| 22 | +---@param buf integer |
| 23 | +---@param f fun(): string |
| 24 | +function M.profile(buf, f) |
| 25 | + local start_ns = vim.uv.hrtime() |
| 26 | + local result = f() |
| 27 | + local time = (vim.uv.hrtime() - start_ns) / 1e+6 |
| 28 | + |
| 29 | + if stats[buf] == nil then |
| 30 | + stats[buf] = {} |
| 31 | + end |
| 32 | + local buf_stats = stats[buf] |
| 33 | + if buf_stats[result] == nil then |
| 34 | + buf_stats[result] = {} |
| 35 | + end |
| 36 | + local times = buf_stats[result] |
| 37 | + table.insert(times, time) |
| 38 | +end |
| 39 | + |
| 40 | +function M.dump_stats() |
| 41 | + local output_stats = {} |
| 42 | + for buf, buf_stats in pairs(stats) do |
| 43 | + local results = {} |
| 44 | + for name, times in pairs(buf_stats) do |
| 45 | + results[name] = M.compute_stats(times) |
| 46 | + end |
| 47 | + ---@type render.md.OutputStat |
| 48 | + local output_stat = { |
| 49 | + path = util.file_path(buf), |
| 50 | + size = util.file_size_mb(buf), |
| 51 | + results = results, |
| 52 | + } |
| 53 | + table.insert(output_stats, output_stat) |
| 54 | + end |
| 55 | + if #output_stats > 0 then |
| 56 | + local file = assert(io.open('stats.json', 'w')) |
| 57 | + file:write(vim.fn.json_encode(output_stats)) |
| 58 | + file:close() |
| 59 | + end |
| 60 | +end |
| 61 | + |
| 62 | +---@private |
| 63 | +---@param times number[] |
| 64 | +---@return render.md.OutputResultStat |
| 65 | +function M.compute_stats(times) |
| 66 | + local min = times[1] |
| 67 | + local max = 0 |
| 68 | + local sum = 0 |
| 69 | + for _, time in ipairs(times) do |
| 70 | + min = math.min(min, time) |
| 71 | + max = math.max(max, time) |
| 72 | + sum = sum + time |
| 73 | + end |
| 74 | + ---@type render.md.OutputResultStat |
| 75 | + return { |
| 76 | + n = #times, |
| 77 | + min = min, |
| 78 | + max = max, |
| 79 | + sum = sum, |
| 80 | + mean = sum / #times, |
| 81 | + } |
| 82 | +end |
| 83 | + |
| 84 | +return M |
0 commit comments