lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, 28 Jul 2009 06:18:04 +0300, David Manura <dm.lua@math2.org> wrote:

I was thinking of posting something on this exact performance problem
with lua_cpcall allocating a new function object on each call.  The
allocation can be avoided.  In brief....first construct a Lua C
function that when executed calls the C function pointer stored in the
lightuserdata passed as the first argument.  This is done only once.
Now, whenever you need to call a C function, lua_pushvalue that Lua C
function mentioned previously, lua_pushlightuserdata the C function
pointer you want to call, and finally do the lua_pcall.  All three
operations never longjump and are safe, assuming you have sufficient
stack space.  The approach does assume that C function pointers can
fit inside a lightuserdata, which is usually safe in practice.  I had
done some micro-benchmarking of this and got a good speedup.

May I ask how big was your speedup?
I just tried microbenchmark with lua_cpcall and the following:

int my_auxcpcall(lua_State *L) {
    lua_CFunction f = (lua_CFunction) lua_topointer(L, -1);
    lua_pop(L, 1);
    return f(L);
}

int my_cpcall(lua_State *L, lua_CFunction func, void *ud) {
lua_pushvalue(L, myauxcpcallIdx); /* global reference index that has my_auxcpcall CFunction value */
    lua_pushlightuserdata(L, ud);
    lua_pushlightuserdata(L, (void *) func);
    return lua_pcall(L, 2, 0, 0);
}

and got 0.15 vs 0.22 seconds on 1000000 calls on core2, and 40 vs 47 seconds on mips.
I was expecting something more spectacular...