coanor
coanor

Reputation: 3962

what is the fasted way to call Lua from C?

I have an HTTP server that needs to handle HTTP requests from Lua code. From C code, I call some Lua C API this way (idea comes from here):

lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, "some.lua");
lua_pcall(L, 0, 0, 0);   /* preload */
lua_getglobal(L, "handle");
lua_pushstring(L, "http_request");
lua_pcall(L, 1, 1, 0);
lua_close(L);

This bunch of code is run for every HTTP request. In multi-thread worker context, this code has a considerable performance cost (from 20000tps to 100tps). I wonder is there was more efficient way to call Lua code from C?


Update

When I comment out all these Lua C API calls, I can make a 20000tps. But when open this API calling, 100tps. When make some changes in some.lua (remove the require call, only load a empty Lua file), then performance comes to about 15000tps.

So, at lease, these API calling cost about 5000tps, how to make this API calling more faster?

Upvotes: 3

Views: 992

Answers (1)

Deco
Deco

Reputation: 5159

Use a thread-safe queue per Lua state and have the state pop from the queue in an infinite loop. If the queue is empty, have the state wait on a condition that is triggered upon insertion into the queue. I suggest LuaJIT, as it will optimise the raw threading API calls to approach near-C speeds.

Unless you are handling large amounts of HTTP requests, this will not benefit you significantly (as mentioned by dsign).

Note: this approach involves the reuse of Lua states for multiple requests. If this is a security problem, you might be able to do something with per-session Lua states with an expiration timeout... but I'm not sure. (It'd be an interesting experiment in stateful server-client partnerships! You could use the Lua state to hold the user's entire session and then resume from sleep when there's a new request... which would be fast.)

Upvotes: 2

Related Questions