C调用lua脚本的效率测试

转自:http://www.cppblog.com/jinq0123/archive/2009/02/17/73998.aspx

 

C调用lua脚本的效率测试

 

以下代码以C语言为基准,测试了C调用Lua循环和循环调用Lua的效率。结论是不要频繁地穿越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 脚本里面的函数由C调用
int use_lua_add(lua_State *L, const char *func_name, int x, int y)
{
    int sum;                        /* 通过名字得到Lua函数 */
    lua_getglobal(L, func_name);    /* 第一个参数 */
    lua_pushnumber(L, x);           /* 第二个参数 */
    lua_pushnumber(L, y);           /* 调用函数,告知有两个参数,一个返回值 */
    lua_call(L, 2, 1);              /* 得到结果 */
    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;
}

运行结果:

C++: 31ms.
The sum is 20000000.
Lua loop_add: 437ms.
The sum is 20000000.
Loop lua add: 2360ms.
The sum is 20000000.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值