首頁  >  文章  >  web前端  >  asm.js & webassembly-WEB的高效能運算

asm.js & webassembly-WEB的高效能運算

php中世界最好的语言
php中世界最好的语言原創
2017-11-18 14:46:042144瀏覽

之前先跟大家介紹過WebWorkers-WEB的高效能運算,關於javascript的知識都很有意思,那麼今天給大家說一說asm.js & webassembly與WEB高效能運算的關係,之前我們說過要解決高效能運算的兩個方法,一個是並發用WebWorkers,另一個就是用更底層的靜態語言。

2012年,Mozilla的工程師Alon Zakai在研究LLVM編譯器時突發奇想:能不能把C/C++編譯成Javascript,並且盡量達到Native程式碼的速度呢?於是他開發了Emscripten編譯器,用來將C/C++程式碼編譯成Javascript的子集asm.js,效能差不多是原生程式碼的50%。大家可以看看這個PPT。


之後Google開發了Portable Native Client,也是能讓瀏覽器運作C/C++程式碼的技術。 後來估計大家都覺得各搞各的不行啊,居然Google, Microsoft, Mozilla, Apple等幾家大公司一起合作開發了一個面向Web的通用二進制和文本格式的項目,那就是WebAssembly,官網上的介紹是:


WebAssembly or wasm is a new portable, size- and load-time-efficient format suitable for compilation to the web.


#WebAssembly is currently being designed as an open standard by a W3C Community Group that includes representatives from all major browsers.


#所以,WebAssembly好的項目。我們可以看一下目前瀏覽器的支援情況: 

asm.js & webassembly-WEB的高效能運算



#安裝Emscripten


訪問https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html


#1. 下載對應平台版本的SDK


2. 透過em​​sdk取得最新版工具

# Fetch the latest registry of available tools.
./emsdk update
 
# Download and install the latest SDK tools.
./emsdk install latest
 
# Make the "latest" SDK "active" for the current user. (writes ~/.emscripten file)
./emsdk activate latest
 
# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh


3.將下列加入環境變數PATH中

~/emsdk-portable
~/emsdk-portable/clang/fastcomp/build_incoming_64/bin
~/emsdk-portable/emscripten/incoming


4.其他


##我執行的時候碰到報錯說LLVM版本不對,後來參考文件配置了LLVM_ROOT變數就好了,如果你沒有遇到問題,可以忽略。

LLVM_ROOT = os.path.expanduser(os.getenv('LLVM', '/home/ubuntu/a-path/emscripten-fastcomp/build/bin'))


5. 驗證是否安裝好


#執行emcc -v,如果安裝好會出現以下資訊:

emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 1.37.21
clang version 4.0.0 (https://github.com/kripken/emscripten-fastcomp-clang.git 974b55fd84ca447c4297fc3b00cefb6394571d18) (https://github.com/kripken/emscripten-fastcomp.git 9e4ee9a67c3b67239bd1438e31263e2e86653db5) (emscripten 1.37.21 : 1.37.21)
Target: x86_64-apple-darwin15.5.0
Thread model: posix
InstalledDir: /Users/magicly/emsdk-portable/clang/fastcomp/build_incoming_64/bin
INFO:root:(Emscripten: Running sanity checks)

Hello, WebAssembly!


#建立一個檔案hello.c:

#include <stdio.h>
int main() {
  printf("Hello, WebAssembly!\n");
  return 0;
}

編譯C/C++程式碼:

emcc hello.c

上述指令會產生一個a.out.js文件,我們可以直接用Node.js執行:

node a.out.js

輸出

Hello, WebAssembly!

為了讓程式碼運行在網頁裡面,執行下面指令會產生hello.html和hello.js兩個文件,其中hello.js和a.out.js內容是完全一樣的。

emcc hello.c -o hello.html<code>
 
➜  webasm-study md5 a.out.js
MD5 (a.out.js) = d7397f44f817526a4d0f94bc85e46429
➜  webasm-study md5 hello.js
MD5 (hello.js) = d7397f44f817526a4d0f94bc85e46429

然後在瀏覽器開啟hello.html,可以看到頁面

asm.js & webassembly-WEB的高效能運算

前面產生的程式碼都是asm.js,畢竟Emscripten是人家作者Alon Zakai最早用來產生asm.js的,預設輸出asm.js也就不足為奇了。當然,可以透過option產生wasm,會產生三個檔案:hello-wasm.html, hello-wasm.js, hello-wasm.wasm。

emcc hello.c -s WASM=1 -o hello-wasm.html

然後瀏覽器開啟hello-wasm.html,發現報錯TypeError: Failed to fetch。原因是wasm檔案是透過XHR非同步載入的,用

file:////存取會報錯,所以我們需要啟動一個伺服器。

npm install -g serve
serve

然後訪問http://localhost:5000/hello-wasm.html,就可以看到正常結果了。

呼叫C/C++函數

前面的Hello, WebAssembly!都是main函數直接打出來的,而我們使用WebAssembly的目的是為了高效能運算,做法多半是用C/ C++實作某個函式進行耗時的計算,然後編譯成wasm,暴露給js去呼叫。


在檔案add.c中寫如下程式碼:

#include <stdio.h>
int add(int a, int b) {
  return a + b;
}
 
int main() {
  printf("a + b: %d", add(1, 2));
  return 0;
}

有兩種方法可以把add方法暴露出來給js呼叫。

透過命令列參數暴露API

emcc -s EXPORTED_FUNCTIONS="[&#39;_add&#39;]" add.c -o add.js

注意方法名稱add前必須加_。 然後我們可以在Node.js裡面這樣使用:

// file node-add.js
const add_module = require(&#39;./add.js&#39;);
console.log(add_module.ccall(&#39;add&#39;, &#39;number&#39;, [&#39;number&#39;, &#39;number&#39;], [2, 3]));

執行node node-add.js會輸出5。 如果需要在web頁面使用的話,執行:

emcc -s EXPORTED_FUNCTIONS="[&#39;_add&#39;]" add.c -o add.html

然後在產生的add.html中加入以下程式碼:

<button onclick="nativeAdd()">click</button>
  <script type=&#39;text/javascript&#39;>
    function nativeAdd() {
      const result = Module.ccall(&#39;add&#39;, &#39;number&#39;, [&#39;number&#39;, &#39;number&#39;], [2, 3]);
      alert(result);
    }
  </script>

然後點擊button,就可以看到執行結果了。

Module.ccall會直接調用C/C++程式碼的方法,更通用的場景是我們取得到一個包裝過的函數,可以在js裡面反覆調用,這需要用Module.cwrap,具體細節可以參看文檔。

const cAdd = add_module.cwrap(&#39;add&#39;, &#39;number&#39;, [&#39;number&#39;, &#39;number&#39;]);
console.log(cAdd(2, 3));
console.log(cAdd(2, 4));

定義函數的時候加入EMSCRIPTEN_KEEPALIVE

新增檔案add2.c。

#include <stdio.h>
#include <emscripten.h>
int EMSCRIPTEN_KEEPALIVE add(int a, int b) {
  return a + b;
}
 
int main() {
  printf("a + b: %d", add(1, 2));
  return 0;
}

執行指令:

emcc add2.c -o add2.html

同樣在add2.html中加入程式碼:

<button onclick="nativeAdd()">click</button>
  <script type=&#39;text/javascript&#39;>
    function nativeAdd() {
      const result = Module.ccall(&#39;add&#39;, &#39;number&#39;, [&#39;number&#39;, &#39;number&#39;], [2, 3]);
      alert(result);
    }
  </script>

但是,當你點擊button的時候,報錯:

Assertion failed: the runtime was exited (use NO_EXIT_RUNTIME to keep it alive after main() exits)

可以通过在main()中添加emscripten_exit_with_live_runtime()解决:

#include <stdio.h>
#include <emscripten.h>
 
int EMSCRIPTEN_KEEPALIVE add(int a, int b) {
  return a + b;
}
 
int main() {
  printf("a + b: %d", add(1, 2));
  emscripten_exit_with_live_runtime();
  return 0;
}

或者也可以直接在命令行中添加-s NO_EXIT_RUNTIME=1来解决,

emcc add2.c -o add2.js -s NO_EXIT_RUNTIME=1

不过会报一个警告:

exit(0) implicitly called by end of main(), but noExitRuntime, so not exiting the runtime (you can use emscripten_force_exit, if you want to force a true shutdown)exit(0) implicitly called by end of main(), but noExitRuntime, so not exiting the runtime (you can use emscripten_force_exit, if you want to force a true shutdown)

所以建议采用第一种方法。

上述生成的代码都是asm.js,只需要在编译参数中添加-s WASM=1中就可以生成wasm,然后使用方法都一样。

用asm.js和WebAssembly执行耗时计算

前面准备工作都做完了, 现在我们来试一下用C代码来优化前一篇中提过的问题。代码很简单:

// file sum.c
#include <stdio.h>
// #include <emscripten.h>
 
long sum(long start, long end) {
  long total = 0;
  for (long i = start; i <= end; i += 3) {
    total += i;
  }
  for (long i = start; i <= end; i += 3) {
    total -= i;
  }
  return total;
}
 
int main() {
  printf("sum(0, 1000000000): %ld", sum(0, 1000000000));
  // emscripten_exit_with_live_runtime();
  return 0;
}

注意用gcc编译的时候需要把跟emscriten相关的两行代码注释掉,否则编译不过。 我们先直接用gcc编译成native code看看代码运行多块呢?

➜  webasm-study gcc sum.c
➜  webasm-study time ./a.out
sum(0, 1000000000): 0./a.out  5.70s user 0.02s system 99% cpu 5.746 total
➜  webasm-study gcc -O1 sum.c
➜  webasm-study time ./a.out
sum(0, 1000000000): 0./a.out  0.00s user 0.00s system 64% cpu 0.003 total
➜  webasm-study gcc -O2 sum.c
➜  webasm-study time ./a.out
sum(0, 1000000000): 0./a.out  0.00s user 0.00s system 64% cpu 0.003 total

可以看到有没有优化差别还是很大的,优化过的代码执行时间是3ms!。really?仔细想想,我for循环了10亿次啊,每次for执行大概是两次加法,两次赋值,一次比较,而我总共做了两次for循环,也就是说至少是100亿次操作,而我的mac pro是2.5 GHz Intel Core i7,所以1s应该也就执行25亿次CPU指令操作吧,怎么可能逆天到这种程度,肯定是哪里错了。想起之前看到的一篇rust测试性能的文章,说rust直接在编译的时候算出了答案, 然后把结果直接写到了编译出来的代码里, 不知道gcc是不是也做了类似的事情。在知乎上GCC中-O1 -O2 -O3 优化的原理是什么?这篇文章里, 还真有loop-invariant code motion(LICM)针对for的优化,所以我把代码增加了一些if判断,希望能“糊弄”得了gcc的优化。

#include <stdio.h>
// #include <emscripten.h>
 
// long EMSCRIPTEN_KEEPALIVE sum(long start, long end) {
long sum(long start, long end) {
  long total = 0;
  for (long i = start; i <= end; i += 1) {
    if (i % 2 == 0 || i % 3 == 1) {
      total += i;
    } else if (i % 5 == 0 || i % 7 == 1) {
      total += i / 2;
    }
  }
  for (long i = start; i <= end; i += 1) {
    if (i % 2 == 0 || i % 3 == 1) {
      total -= i;
    } else if (i % 5 == 0 || i % 7 == 1) {
      total -= i / 2;
    }
  }
  return total;
}
 
int main() {
  printf("sum(0, 1000000000): %ld", sum(0, 100000000));
  // emscripten_exit_with_live_runtime();
  return 0;
}


执行结果大概要正常一些了。

➜  webasm-study gcc -O2 sum.c
➜  webasm-study time ./a.out
sum(0, 1000000000): 0./a.out  0.32s user 0.00s system 99% cpu 0.324 total

ok,我们来编译成asm.js了。

#include <stdio.h>
#include <emscripten.h>
 
long EMSCRIPTEN_KEEPALIVE sum(long start, long end) {
// long sum(long start, long end) {
  long total = 0;
  for (long i = start; i <= end; i += 1) {
    if (i % 2 == 0 || i % 3 == 1) {
      total += i;
    } else if (i % 5 == 0 || i % 7 == 1) {
      total += i / 2;
    }
  }
  for (long i = start; i <= end; i += 1) {
    if (i % 2 == 0 || i % 3 == 1) {
      total -= i;
    } else if (i % 5 == 0 || i % 7 == 1) {
      total -= i / 2;
    }
  }
  return total;
}
 
int main() {
  printf("sum(0, 1000000000): %ld", sum(0, 100000000));
  emscripten_exit_with_live_runtime();
  return 0;
}
执行
emcc sum.c -o sum.html


然后在sum.html中添加代码

<button onclick="nativeSum()">NativeSum</button>
  <button onclick="jsSumCalc()">JSSum</button>
  <script type=&#39;text/javascript&#39;>
    function nativeSum() {
      t1 = Date.now();
      const result = Module.ccall(&#39;sum&#39;, &#39;number&#39;, [&#39;number&#39;, &#39;number&#39;], [0, 100000000]);
      t2 = Date.now();
      console.log(`result: ${result}, cost time: ${t2 - t1}`);
    }
  </script>
  <script type=&#39;text/javascript&#39;>
    function jsSum(start, end) {
      let total = 0;
      for (let i = start; i <= end; i += 1) {
        if (i % 2 == 0 || i % 3 == 1) {
          total += i;
        } else if (i % 5 == 0 || i % 7 == 1) {
          total += i / 2;
        }
      }
      for (let i = start; i <= end; i += 1) {
        if (i % 2 == 0 || i % 3 == 1) {
          total -= i;
        } else if (i % 5 == 0 || i % 7 == 1) {
          total -= i / 2;
        }
      }
 
      return total;
    }
    function jsSumCalc() {
      const N = 100000000;// 总次数1亿
      t1 = Date.now();
      result = jsSum(0, N);
      t2 = Date.now();
      console.log(`result: ${result}, cost time: ${t2 - t1}`);
    }
  </script>
另外,我们修改成编译成WebAssembly看看效果呢?
emcc sum.c -o sum.js -s WASM=1

感觉Firefox有点不合理啊, 默认的JS太强了吧。然后觉得webassembly也没有特别强啊,突然发现emcc编译的时候没有指定优化选项-O2。再来一次:

emcc -O2 sum.c -o sum.js # for asm.js
emcc -O2 sum.c -o sum.js -s WASM=1 # for webassembly

居然没什么变化, 大失所望。号称asm.js可以达到native的50%速度么,这个倒是好像达到了。但是今年Compiling for the Web with WebAssembly (Google I/O ‘17)里说WebAssembly是1.2x slower than native code,感觉不对呢。asm.js还有一个好处是,它就是js,所以即使浏览器不支持,也能当成不同的js执行,只是没有加速效果。当然WebAssembly受到各大厂商一致推崇,作为一个新的标准,肯定前景会更好,期待会有更好的表现。

这就是asm.js & webassembly与web高性能计算的关系了,之后还有想法写一份结合Rust做WebAssembly的文章,有兴趣的朋友可以持续关注。


以上是asm.js & webassembly-WEB的高效能運算的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn