编程文汇

luajit与c执行效率简单比较

#1

程序是我一直用来比较的一个片段:

纯c:

static void test() {
     auto start = ezg::util::now();
     int ret = 0;
     int N = 2000000000+1;
     int M = 123;
     for (int i = 0; i < N; i++) {
       ret = ezg_add(ret, (i % M));
       ret = ret % M;
     }
     auto time = ezg::util::now() - start;
     ezg::logger::log(std::to_string(ret));
     ezg::logger::log(std::to_string(time));
   }


x64 release:
log     69
log     11212(毫秒)
 纯lua:

N = 2000000000
M = 123

function testlocal()
    start = os.clock()
    ret = 0;
    for i=0,N,1 do  
        ret = ret+(i%M)
        ret = ret%M
    end  
    time = os.clock()-start
    print(ret)
    print(time)
end
testlocal() 

64位输出:
69
30.252秒
lua调用c:
 
local ffi = require("ffi")
ffi.cdef[[
    int ezg_add(int a, int b);
]]
local ezg = ffi.load("ezg") 
function testnativecall()
    start = os.clock()
    ret = 0;
    for i=0,N,1 do  
        ret = ezg.ezg_add(ret,(i%M))
        ret = ret%M
    end  
    time = os.clock()-start
    print(ret)
    print(time)
end
testnativecall() 

64位 :
69
32.102 秒 
java

public class Main
{
    static {
        System.loadLibrary("ezg"); 
     }
    private static native int ezg_add(int a,int b);
    static final int N = 2000000000;
    static final int M = 123;
    public static void main(String[] args) {
        test2();
    }

    static void test2 ()
    {
        long start = System.currentTimeMillis();
        int ret = 0;
        for (int i = 0; i < N; i++)
        {
            ret = ezg_add (ret,(i % M)); 
            ret %= M;
        }
        System.out.println((System.currentTimeMillis() - start) );
        System.out.println(ret);
    }

    static void test1 ()
    {
        long start = System.currentTimeMillis();
        long ret = 0;
        for (int i = 0; i < N; i++)
        {
            ret += (i % M); 
            ret %= M;
        }
        System.out.println((System.currentTimeMillis() - start) );
        System.out.println(ret);
    }
} 

纯java:
12622
69

java jni:
34812
69

对比64位的情况,可见luajit本身的执行效率大约是c的:
11.2/30=37%,而lua调用c基本没有额外开销。

前面c# 64位的执行效率:
0.63/0.7 = 90%,
c#调用c:
0.63/2.51 = 25% 

总体效率对比

c	100%
luajit	37%
luajit call c	35%
c#	90%
c# call c	25%
java	89%
java jni call c	35%

所以简单的功能尽量自己实现,调用c函数,得不偿失。

0 Likes