简体   繁体   English

从C调用Lua的禁区方式是什么?

[英]what is the fasted way to call Lua from C?

I have an HTTP server that needs to handle HTTP requests from Lua code. 我有一个HTTP服务器,需要处理来自Lua代码的HTTP请求。 From C code, I call some Lua C API this way (idea comes from here ): 从C代码中,我用这种方式调用一些Lua C API(想法来自这里 ):

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. 为每个HTTP请求运行这一堆代码。 In multi-thread worker context, this code has a considerable performance cost (from 20000tps to 100tps). 多线程工作者上下文中,此代码具有相当大的性能成本(从20000tps到100tps)。 I wonder is there was more efficient way to call Lua code from C ? 我想知道从C调用Lua代码有更有效的方法吗?


Update 更新

When I comment out all these Lua C API calls, I can make a 20000tps. 当我注释掉所有这些Lua C API调用时,我可以制作20000tps。 But when open this API calling, 100tps. 但是当打开这个API调用时,100tps。 When make some changes in some.lua (remove the require call, only load a empty Lua file), then performance comes to about 15000tps. some.lua中进行一些更改(删除require调用,只加载一个空的Lua文件),然后性能达到约15000tps。

So, at lease, these API calling cost about 5000tps, how to make this API calling more faster? 那么,这些API调用成本约为5000tps,如何让这个API调用更快?

Use a thread-safe queue per Lua state and have the state pop from the queue in an infinite loop. 每个Lua状态使用一个线程安全的队列,并在无限循环中从队列中弹出状态。 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. 我建议使用LuaJIT,因为它会优化原始线程API调用以接近近C速度。

Unless you are handling large amounts of HTTP requests, this will not benefit you significantly (as mentioned by dsign). 除非您正在处理大量的HTTP请求,否则这不会对您有所帮助(如dsign所述)。

Note: this approach involves the reuse of Lua states for multiple requests. 注意:这种方法涉及为多个请求重用Lua状态。 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. 如果这是一个安全问题,您可以使用到期超时的每会话Lua状态执行某些操作......但我不确定。 (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.) (这是有状态服务器 - 客户端合作伙伴关系中的一个有趣的实验!你可以使用Lua状态来保存用户的整个会话,然后在有新请求时从睡眠状态恢复......这会很快。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM