C調(diào)用lua腳本的效率測(cè)試
以下代碼以C語(yǔ)言為基準(zhǔn),測(cè)試了C調(diào)用Lua循環(huán)和循環(huán)調(diào)用Lua的效率。結(jié)論是不要頻繁地穿越C/Lua邊界.
代碼整理自:http://blog.csdn.net/Tomorrow/archive/2008/06/11/2536884.aspx
#include <time.h>extern "C"{#include "lua.h"#include "lualib.h"#include "lauxlib.h"}/* Lua解釋器指針 */const char LUA_SCRIPT[] = "function loop_add(a, b) " " local sum = 0 " " for i = 1, 10000000 do " " sum = sum + a + b " " end " " return sum " "end " " " "function add(a, b) " " return a + b " "end " ;// lua 腳本里面的函數(shù)由C調(diào)用int use_lua_add(lua_State *L, const char *func_name, int x, int y){ int sum; /* 通過(guò)名字得到Lua函數(shù) */ lua_getglobal(L, func_name); /* 第一個(gè)參數(shù) */ lua_pushnumber(L, x); /* 第二個(gè)參數(shù) */ lua_pushnumber(L, y); /* 調(diào)用函數(shù),告知有兩個(gè)參數(shù),一個(gè)返回值 */ lua_call(L, 2, 1); /* 得到結(jié)果 */ 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;}
運(yùn)行結(jié)果:
C++: 31ms.The sum is 20000000.Lua loop_add: 437ms.The sum is 20000000.Loop lua add: 2360ms.The sum is 20000000.
Powered by: C++博客 Copyright © 金慶