IT/web assembly

web assembly

seyeonHello 2022. 3. 11. 15:15

Web Assembly

웹에서 c/c++언어로 작성된 코드를 실행할 수 있도록 하는 저수준의 언어(어셈블리와 유사한 텍스트 형식)

웹어셈블리를 사용해서 네이티브에 가까운 속도를 낼 수 있습니다.

직접 웹 어셈블리어를 작성하는 것이 아닌, web assembly의 compiler toolchain인 emscripten를 사용해서 만들어줍니다.

flow

아래 emscripten download 가이드 라인을 확인하세요

https://emscripten.org/docs/getting_started/downloads.html

 

Download and install — Emscripten 3.1.6-git (dev) documentation

Note If you want to use your system’s Node.js instead of the emsdk’s, it may be node instead of nodejs, and you can adjust the NODE_JS attribute of your .emscripten file to point to it.

emscripten.org

# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git

# Enter that directory
cd emsdk

# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull

# 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

 

이제 간단한 소스코드로 웹 어셈블리 모듈을 만들어보겠습니다.

main.c파일을 생성 후 임의로 코드를 작성하였습니다. 하나의 for문이 10^6번 실행되었을 때 걸리는 시간(msec)을 측정하는 코드입니다.

//main.c
#include <time.h>
#include <stdio.h>

int main(){
	clock_t beg=clock();
	for(int i=0;i<1000000;i++){}
	clock_t end=clock();
	long msec=end-beg;
	printf("%ld\n",msec);
	return 0;
}

 

웹 어셈블리를 만들기 위해 emscripten 명령어를 실행해봅니다.

emcc main.c -o main.html

(지금은 간단한 케이스이지만, 복잡한 코드의 경우 추가적인 옵션을 설정해야할 필요가 있습니다.)

https://emscripten.org/docs/porting/Debugging.html?highlight=profilling%20funcs 

 

Debugging — Emscripten 3.1.6-git (dev) documentation

Emcc strips out most of the debug information from optimized builds by default. Optimisation levels -O1 and above remove LLVM debug information, and also disable runtime ASSERTIONS checks. From optimization level -O2 the code is minified by the Closure Com

emscripten.org

 

그러면 main.wasm을 포함한 main.js, main.html이 생성됩니다. main.js는 간단하게 설명하면 main.wasm를 불러와서 실행시켜주는 글루코드의 역할을 합니다. main.html을 live-server로 실행시켜주면 아래와 같이 출력 화면을 확인할 수 있습니다.

웹 실행 화면

(작성중)

참고 자료

'IT > web assembly' 카테고리의 다른 글

web assembly 메모리 사용기  (0) 2022.10.12
toolchain for cross-compiling to JS using Emscripten  (0) 2022.07.04