DEV Community

Cover image for So, you can benchmark in AssemblyScript...
JairusSW
JairusSW

Posted on

So, you can benchmark in AssemblyScript...

Introducing... Astral--A minimalistic benchmarking library for AssemblyScript. Based off of criterion.rs.
With this new benchmarking tool, we are able to easily visualize and optimize performance in our code precisely. Usually, we would have to use a while loop and Date.now or performance.now bindings to measure performance. Astral adds warmup periods, logging, and a few other tools. Lets get started!
In an existing AssemblyScript project, install as-tral.

npm i -D @as-tral/cli
Enter fullscreen mode Exit fullscreen mode

Next, create a benches folder in your assembly directory. Add a file named as-tral.d.ts in there.

assembly/
└── __benches__/
    └── as-tral.d.ts
Enter fullscreen mode Exit fullscreen mode

In as-tral.d.ts, copy and paste

/// <reference path="../../node_modules/@as-tral/cli/as-tral.d.ts" />
Enter fullscreen mode Exit fullscreen mode

Stick any file with a .ts extension in benches. You can even have multiple.

assembly/
└── __benches__/
    ├── as-tral.d.ts
    └── my-benchmark.ts
Enter fullscreen mode Exit fullscreen mode

Your benchmark will live in this file. Let's create an example benchmark.

// to ensure accurate benchmarks, we must make sure that binaryen doesn't do any sneaky
// optimizations on our input without us knowing. Thus, we must use `blackbox`.
const input = blackbox("The quick brown fox jumped over the lazy dog.".repeat(10));

// our string here must be a compile time constant.
// open an issue if you'd like to see this constraint lifted.
bench("string split", () => {
    // this function body will be run many times.
    // we must make sure our compiler won't throw away the computation,
    // so we use `blackbox` here again.
    blackbox(input.split(" "));
});
Enter fullscreen mode Exit fullscreen mode

Now, let's run as-tral.

rom@i9-cabin:~/demo$ npx astral
Compiling assembly/__benches__/hello.ts

Benchmarking string split: Warming up for 3000ms
Benchmarking string split: Collecting 100 samples in estimated 5018.6ms (1.2M iterations)
Benchmarking string split: Analyzing
string split            time: [3770.9ns 3775ns 3778.9ns]
Found 4 outliers among 100 measurements (4%)
  3 (3%) low mild
  1 (1%) high mild
Enter fullscreen mode Exit fullscreen mode

Pretty great!

Top comments (0)