为什么我在Webassembly中导出的quicksort比纯JavaScript实现要慢?

时间:2018-11-28 03:41:13

标签: javascript emscripten webassembly

我已经用纯Javascript和C语言实现了一个非常幼稚的quicksort,后来将其导出为WebAssembly模块。

我正在对[0; 1000]范围内的10个 6 整数的两个相同数组进行排序。 纯javascript实现平均需要780毫秒,而基于WebAssembly的则需要935毫秒(如果未设置优化标志,则需要1020毫秒)。

为什么纯JavaScript实现最快?

在以下2个实现中:

JS:

void swap(int *array, int swapy1, int swapy2) {
    int tmp = array[swapy1];
    array[swapy1] = array[swapy2];
    array[swapy2] = tmp;
  }


  int partition(int *array, int lo, int hi) {
    int pivot = array[hi];
    int i = lo - 1;
    for (int j = lo; j < hi; j++) {
      if (array[j] < pivot) {
        if (i != j) {
          i++;
          swap(array, i, j);
        }
      }
    }
    i++;
    swap(array, i, hi);
    return i;
  }

  void sort(int *array, int lo, int hi) {
    if (lo < hi) {
      int p = partition(array, lo, hi);
      sort(array, lo, p - 1);
      sort(array, p + 1, hi);
    }
  }

  void quicksort(int *array, int lo, int hi, char *exp) {
   struct timeval t1, t2;
   double elapsedTime;

    gettimeofday(&t1, NULL);
    sort(array, lo, hi);
    gettimeofday(&t2, NULL);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms

    printf(" - 10%s entries sorted in %.0f ms\n", exp, elapsedTime);
  }

C:

WasmModule().then(wasm => {
    console.log("Monothreaded Lomuto Quicksort, WebAssembly");
    function callWasm(array, exponant) {
      let heapBuf = wasm._malloc(array.length * Uint32Array.BYTES_PER_ELEMENT);
      wasm.HEAP32.set(array, heapBuf / 4);
      wasm.ccall('quicksort', null, ['number', 'number', 'number', 'string'], [heapBuf, 0, array.length - 1, exponant]);
      wasm._free(heapBuf);
    }
    millionIntCopy = millionInt.slice();
    tenMillionIntCopy = tenMillionIntCopy.slice();
    callWasm(millionIntCopy, "\u2076");
    // callWasm(tenMillionIntCopy, "\u2077"); // stack overflow
    // callWasm(hundredMillionInt, "\u2078"); stackoverflow
  })

调用者代码(通过emscripten Module对象):

classofmethods new1 = new classofmethods();
static getset GS = new GS();
.....
code .....
settle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String keyword1 = nc.methodName(String, String, int);
GS.setkeyword(keyword1);
try {
//Method 1 makes an API call...Trying to set an //endpoint but the URL prints out as ....keyword=null;
new1.method1();
new1.method2();
new1.method3();
new1.method4();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 }
  });

可以找到完整的项目here

0 个答案:

没有答案
相关问题