CCallLua scriptEfficiencyTestIs the content to be introduced in this article. The following code usesCLanguage as the benchmark,TestNowCCallLuaLoop and loop callLua. The conclusion is that do not traverse frequentlyC/LuaBoundary.
- # Include <time. h>
-
- Extern "C"
- {
- # Include "lua. h"
- # Include "lualib. h"
- # Include "lauxlib. h"
- }/* Lua interpreter pointer */
-
- Const char LUA_SCRIPT [] =
- "Function loop_add (a, B )"
- "Local sum = 0"
- "For I = 1, 10000000 do"
- "Sumsum = sum + a + B"
- "End"
- "Return sum"
- "End"
- ""
- "Function add (a, B )"
- "Return a + B"
- "End"
- ;
-
- // The functions in the lua script are called by C.
- Int use_lua_add (lua_State * L, const char * func_name, int x, int y)
- {
- Int sum;/* obtain the Lua function by name */
- Lua_getglobal (L, func_name);/* The first parameter */
- Lua_pushnumber (L, x);/* second parameter */
- Lua_pushnumber (L, y);/* call the function to inform that there are two parameters, one returned value */
- Lua_call (L, 2, 1);/* get the result */
- Sum = (int) lua_tointeger (L,-1 );
- Lua_pop (L, 1 );
- Return sum;
- }
-
- Int main ()
- {
- Int I, sum = 0;
- Clock_t tStart, tStop;
-
- Lua_State * L = lua_open ();/* opens Lua */
- LuaL_openlibs (L );
- If (luaL_dostring (L, LUA_SCRIPT) // Run lua script
- {
- Printf ("run script failed/n ");
- Lua_close (L );
- Return-1;
- }
-
- Sum = 0;
- TStart = clock ();
- For (I = 0; I <10000000; I ++)
- {
- Sum + = 1 + 1;
- }
- TStop = clock ();
- Printf ("C ++: % dms./nThe sum is % u./n ",
- (TStop-tStart) * 1000/CLOCKS_PER_SEC, sum );
-
- Sum = 0;
- TStart = clock ();
- Sum = use_lua_add (L, "loop_add", 1, 1 );
- TStop = clock ();
- Printf ("Lua loop_add: % dms./nThe sum is % u./n ",
- (TStop-tStart) * 1000/CLOCKS_PER_SEC, sum );
- Sum = 0;
- TStart = clock ();
- For (I = 0; I <10000000; I ++)
- {
- Sum + = use_lua_add (L, "add", 1, 1 );
- }
- TStop = clock ();
- Printf ("Loop lua add: % dms./nThe sum is % u./n ",
- (TStop-tStart) * 1000/CLOCKS_PER_SEC, sum );
- Lua_close (L );
- Return 0;
- }
Running result:
- C++: 31ms.
- The sum is 20000000.
- Lua loop_add: 437ms.
- The sum is 20000000.
- Loop lua add: 2360ms.
- The sum is 20000000.
Summary: DetailsCCallLua scriptEfficiencyTestI hope this article will help you!