c++调用lua脚本测试执行效率

//下载lua源代码,编译生成luaXX.lib, luaXX.dll,将这两个文件及lua.h, lualib.h, lauxlib.h, luaconf.h拷贝到程序当前目录

#include 
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
};

#pragma comment(lib, "lua51.lib") //<加载lua链接库
lua_State *L;    //<创建全局lua对象指针

long long use_lua_fun(lua_State *L, const char funName[], int a, int b)
{
lua_getglobal(L, funName);    //<获取函数名称
lua_pushnumber(L, a);     //<压栈第1个参数
lua_pushnumber(L, b);     //<压栈第2个参数
int ret = lua_pcall(L, 2, 1, 0);    //<调用lua脚本函数,2表示有两个个参数,1表示1个返回结果
if(ret != 0)
{
   printf("lua_call errors:%d\n ,%s",ret, lua_tostring(L, -1));
   return -1;
}
long long sum = (long long)lua_tointeger(L, -1); //<将栈顶转换成longlong型数据
lua_pop(L, 1);        //<弹出第一个元素
return sum;
}

int main()
{
int i;
long long sum = 0;
L = lua_open();        //<初始化lua对象指针
luaL_openlibs(L);       //<加载lua函数库
int ret = luaL_dofile(L, "test.lua"); //<加载脚本,如果脚本编译有错误,则加载失败
if(ret != 0)
{
   printf("dofile errors:%d %s",ret, lua_tostring(L, -1));
   return 1;
}
clock_t start, end;
start = clock();
for(i = 0; i < 4000000; i++)
   sum += 1+2;
end = clock();
printf("In c++, runing time is %d ms %lld\n",(int)(end - start), sum);

start = clock();
sum = use_lua_fun(L, "loopAdd", 1, 2);
end = clock();
printf("lua loopAdd function, runing time is %d ms %lld\n",(int)(end - start), sum);

sum = 0;
start = clock();
for(i = 0; i < 4000000; i++)
   sum += use_lua_fun(L, "add", 1, 2);
end = clock();
printf("c++ loop lua's add function, runing time is %d ms %lld\n",(int)(end - start), sum);

lua_close(L);        //<关闭lua对象指针
return 0;
}

test.lua 脚本内容如下

function add(x,y)
    return x+y;
end

function loopAdd(x,y)
    local sum = 0
    for i = 1,4000000
    do
    sum = sum + x + y
    end
    return sum
end

输出结果

In c++, runing time is 16 ms 12000000
lua loopAdd function, runing time is 219 ms 12000000
c++ loop lua's add function, runing time is 1937 ms 12000000

你可能感兴趣的:(c++调用lua脚本测试执行效率)