Search code examples
luajit

Luajit - why is there a performance drop when restricting standard libraries


Im currently writing a small c program that makes repeated calls to lua functions in a tight loop - and im using luajit to speed things up. One of my requirements is to restrict the standard libraries available to the script. According to this answer, using lua_call to call luaopen_* is the way to do this, however this results in a massive performance hit over using luaL_openlibs.

A small test case of this:

test.c

// gcc -Wall -O3 -o test test.c -lm $(pkg-config --cflags --libs luajit)
#include <luajit.h>
#include <lualib.h>
#include <luaconf.h>
#include <lauxlib.h>
lua_State *LUA = NULL;

int lua_setup(char *filename) {
    LUA = luaL_newstate();
    // lua_pushcfunction(LUA, luaopen_math);
    // lua_pushstring(LUA, LUA_MATHLIBNAME);
    // lua_call(LUA, 1, 0);
    luaL_openlibs(LUA);
    luaL_loadfile(LUA, filename);
    lua_pcall(LUA, 0, 0, 0);
    return 1;
}

int main() {
    lua_setup("test.lua");
    for (int i = 0; i < 10000; i++) {
        lua_getglobal(LUA, "test");
        lua_call(LUA, 0, 1);
        float ret = lua_tonumber(LUA, -1);
        lua_pop(LUA, 1);
    }
    lua_close(LUA);
}

test.lua

function test()
    r = 0
    for i=0,10000 do
        r = r + math.sin(i);
        r = r % 2;
    end
    return r
end

results:

> time ./test 

real    0m1.696s
user    0m1.650s
sys     0m0.000s

after replacing the luaL_openlibs with the commented-out lines

> time ./test 

real    0m6.409s
user    0m6.239s
sys     0m0.004s

Could someone tell me why this occurs? Thanks.


Solution

  • Ok turns out im an idiot. Luajit includes a lua library that needs to be loaded. Adding the following fixed the problem.

    lua_pushcfunction(LUA, luaopen_jit);
    lua_pushstring(LUA, LUA_JITLIBNAME);
    lua_call(LUA, 1, 0);