簡體   English   中英

如何使用 javascript 中的異步函數衡量性能

[英]How to measure performance with async functions in javascript

我創建了一個小應用程序來比較 WebAssembly 和 Javascript 的速度。 令我驚訝的是,JavaScript 在計算大數的階乘時要快得多。 或者至少看起來是這樣。 我很確定這是不對的,是由我使用的 await 語法引起的。 (功能是相同的。)另外,我可以使用哪些非常耗時的任務來比較這兩者? 這看起來並不那么耗時,因為它只需要不到 0.1 毫秒。

AssemblyScript(這被編譯成 wasm)

// The entry file of your WebAssembly module.
export function fib(num: i32): i32 {
  var a: i32 = 1,
    b: i32 = 0,
    temp: i32;

  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

應用程序.js

import waApi from "./api";
...
  <button
       onClick={async () => {
       const t0 = performance.now();
       (await waApi).fib(200);
       const t1 = performance.now();
       this.updateGraph(t1 - t0, "wa");
       const t2 = performance.now();
       this.fib(200);
       const t3 = performance.now();
       this.updateGraph(t3 - t2, "js");
       }}>
Calculate with both 
  </button>

api.js

import { instantiateStreaming } from "assemblyscript/lib/loader";

export default instantiateStreaming(fetch("./assembly.wasm"));

微基准測試(即分析小而非常快的函數的性能的基准測試)的問題在於,您幾乎總是最終會測量錯誤的東西。 您的測量將因以下因素嚴重傾斜:

  • 從 JavaScript 調用 WebAssembly 函數所涉及的開銷
  • AssemblyScript 編譯器(這是非常新的)優化函數的能力
  • 計時器的准確性
  • 您的 JavaScript 引擎達到優化峰值的時間

僅舉幾個!

更現實的基准將執行計算,以執行更大范圍的 WebAssembly 操作,本質上更“現實”(即測量您真正將卸載到 WebAssembly 的負載類型),並且執行時間更長。

這是一個基於 GameBoy 模擬器的更好的基准測試:

https://medium.com/@torch2424/webassembly-is-fast-a-real-world-benchmark-of-webassembly-vs-es6-d85a23f8e193

它應該是

import waApi from "./api";

class Test extends React.Component { 
  async componentDidMount() {
    this.wasmModule = await waApi;
  }

  render() {
    return (
      <button
        onClick={() => {
          const module = this.wasmModule;
          if (!module) {
            console.warn("module not yet loaded. Try later");
            return;
          }
          const t0 = performance.now();
          module.fib(200);
          const t1 = performance.now();
          this.updateGraph(t1 - t0, "wa");
          const t2 = performance.now();
          this.fib(200);
          const t3 = performance.now();
          this.updateGraph(t3 - t2, "js");
        }}>
    );
  }
}

因為在您的 wasm 部分示例中,您還測量了模塊的加載和實例化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM