cheerp 交叉編譯aes庫

這個文章主要演示了一個cheerp交叉編譯的簡單的例子對比測試。這個例子中我們把一個c文件的算法交叉到js側。

先行準備

我們分別使用js的一個aes庫,和交叉過去的一個c實現的庫分別分別在node和瀏覽器端做性能比較。

先把c算法庫交叉到一個bc(clang 的byte code)備用, 驗證好執行正確結果。

clang -c -w $(CHEERP_FLAG) $(WASMFLAGS) -O3 -o ./build/aes.bc aes.c

clang++ -w $(CHEERP_FLAG) $(WASMFLAGS) $(WASM_LOADER) -D_MACRO_WASM_INIT -cheerp-no-math-imul -O3 -o ./build/test.wasm main.cpp ./build/aes.bc

cheerp -wasm 執行結果

node開啓 --wasm-opt 運行
wasm 執行 1000000次結果 397-459ms
chorme
1000000次結果 400-576ms

js + aes.js 執行結果

node 緩存開啓 運行
執行 1000000次結果 2585ms-5600ms
chorme
執行 1000000次結果 3156ms-3500ms

js代碼

var aesjs = this.aesjs;
var zero = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

var key = zero;
//var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// The initialization vector (must be 16 bytes)
var iv = zero;//[ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];

// Convert text to bytes (text must be a multiple of 16 bytes)
var text = '1234567892312710';
var textBytes = aesjs.utils.utf8.toBytes(text);
var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
console.time("time_t node");
for(var i = 0; i< 1000000; i++) {
    
    var encryptedBytes = aesCbc.encrypt(textBytes);
}
console.timeEnd("time_t node");

c++代碼

void test_for_aes_en() {
    aes_context  ctx ;
    uint8 Key[16] ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    uint8 Indata[16]  ={1,2,3,4,5,6,7,8,9,2,3,1,2,7,1};
    uint8 Outdata[16] ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    memset(&ctx,0,sizeof(ctx));
    aes_set_key(&ctx, Key, 16*8);
    aes_encrypt(&ctx, Indata, Outdata);
}

void m007 () {
    long int size_w = 1000000;
    for( long int i = 0 ; i < size_w; i++ ) {
        test_for_aes_en();
    }
}

可以看到,經過LLVM優化過的WASM代碼執行的效率在V8引擎和Node引之上, V8和Node經過jit已經很快了(其他瀏覽器速度更慢,firefox執行了 7852ms),wasm 性能在這幾個平臺移植保持出色和穩定(300-500ms);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章