perf: use timer instead of check for async executor

This commit is contained in:
Folke Lemaitre 2024-06-28 17:44:43 +02:00
parent ab46edbd47
commit f85575ab23
No known key found for this signature in database
GPG Key ID: 41F8B1FBACAE2040
1 changed files with 10 additions and 11 deletions

View File

@ -2,8 +2,10 @@ local M = {}
---@type Async[] ---@type Async[]
M._queue = {} M._queue = {}
M._executor = assert(vim.loop.new_check()) M._executor = assert(vim.loop.new_timer())
M._running = false
M.TIMER = 10
M.BUDGET = 100
---@type table<thread, Async> ---@type table<thread, Async>
M._threads = setmetatable({}, { __mode = "k" }) M._threads = setmetatable({}, { __mode = "k" })
@ -68,11 +70,10 @@ end
---@async ---@async
function Async:sleep(ms) function Async:sleep(ms)
self._suspended = true
vim.defer_fn(function() vim.defer_fn(function()
self._suspended = false self:resume()
end, ms) end, ms)
coroutine.yield() self:suspend()
end end
---@async ---@async
@ -120,12 +121,11 @@ function Async:step()
end end
function M.step() function M.step()
M._running = true local budget = M.BUDGET * 1e6
local budget = 1 * 1e6 local start = vim.uv.hrtime()
local start = vim.loop.hrtime()
local count = #M._queue local count = #M._queue
local i = 0 local i = 0
while #M._queue > 0 and vim.loop.hrtime() - start < budget do while #M._queue > 0 and vim.uv.hrtime() - start < budget do
---@type Async ---@type Async
local state = table.remove(M._queue, 1) local state = table.remove(M._queue, 1)
if state:step() then if state:step() then
@ -136,7 +136,6 @@ function M.step()
break break
end end
end end
M._running = false
if #M._queue == 0 then if #M._queue == 0 then
return M._executor:stop() return M._executor:stop()
end end
@ -146,7 +145,7 @@ end
function M.add(async) function M.add(async)
table.insert(M._queue, async) table.insert(M._queue, async)
if not M._executor:is_active() then if not M._executor:is_active() then
M._executor:start(vim.schedule_wrap(M.step)) M._executor:start(1, M.TIMER, vim.schedule_wrap(M.step))
end end
return async return async
end end