Optimise async callbacks (polling)

call async Rust callback [sum] 3 10
                        time:   [59.338 us 59.729 us 60.097 us]
                        change: [-10.336% -8.6212% -6.8003%] (p = 0.00 < 0.05)
                        Performance has improved.
This commit is contained in:
Alex Orlenko 2021-03-03 23:21:56 +00:00
parent 7cb9c4f39c
commit 726fde7e1f
2 changed files with 15 additions and 6 deletions

View File

@ -13,6 +13,7 @@ extern "system" {}
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use std::time::Duration;
use tokio::runtime::Runtime;
use tokio::task;
use mlua::prelude::*;
@ -117,7 +118,10 @@ fn call_sum_callback(c: &mut Criterion) {
fn call_async_sum_callback(c: &mut Criterion) {
let lua = Lua::new();
let callback = lua
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move { Ok(a + b + c) })
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move {
task::yield_now().await;
Ok(a + b + c)
})
.unwrap();
lua.globals().set("callback", callback).unwrap();

View File

@ -1735,10 +1735,9 @@ impl Lua {
match (*fut).as_mut().poll(&mut ctx) {
Poll::Pending => {
check_stack(state, 6)?;
check_stack(state, 1)?;
ffi::lua_pushboolean(state, 0);
push_gc_userdata(state, AsyncPollPending)?;
Ok(2)
Ok(1)
}
Poll::Ready(results) => {
let results = results?;
@ -1782,18 +1781,24 @@ impl Lua {
))
})?,
)?;
env.set("pending", unsafe {
let _sg = StackGuard::new(self.state);
check_stack(self.state, 5)?;
push_gc_userdata(self.state, AsyncPollPending)?;
self.pop_value()
})?;
// We set `poll` variable in the env table to be able to destroy upvalues
self.load(
r#"
poll = get_poll(...)
local poll, yield, unpack = poll, yield, unpack
local poll, pending, yield, unpack = poll, pending, yield, unpack
while true do
local ready, res, nres = poll()
if ready then
return unpack(res, nres)
end
yield(res)
yield(pending)
end
"#,
)