負荷テストツール k6 –compatibility-mode=base サンプルコード

負荷テストツール k6 を –compatibility-mode=base オプション付きで実行するサンプルコードをご紹介します。

k6 - load testing tool

前提知識 k6 は ES6 コードを動かすと遅い

–compatibility-mode=base

The most impactful option to improve k6 performance is to use –compatibility-mode=base to disable the internal Babel transpilation and run a k6 script written in ES5.1.
k6のパフォーマンスを向上させる最もインパクトのあるオプションは、 –compatibility-mode=base を使用して内部のBabel transpilationを無効にし、 ES5.1で書かれたk6スクリプトを実行することです。

# compatibility-mode=base disables the Babel transpilation and the inclusion of corejs 
k6 run --compatibility-mode=base yourscript.es5.js

Background / 背景

Most k6 script examples and documentation are written in ES6+.
k6スクリプトのサンプルやドキュメントは、ほとんどがES6+で書かれています。

By default, k6 transpiles ES6+ code to ES5.1 using babel and loads corejs to enable commonly used APIs. This works very well for 99% of use cases, but it adds significant overheard with large tests.
デフォルトでは、k6はES6+のコードをbabelを使ってES5.1にトランスパイルし、corejsをロードしてよく使われるAPIを使用できるようにします。これは99%のユースケースで非常にうまく機能しますが、大規模なテストではかなりのオーバーヒートを引き起こします。

When running a ES5.1 script instead of the original ES6+ script, k6 can use about 50-85% of memory and significantly reduce the CPU load and startup time.
オリジナルのES6+スクリプトの代わりにES5.1スクリプトを実行する場合、k6は約50-85%のメモリを使用し、CPU負荷と起動時間を大幅に削減することができます。

引用元: –compatibility-mode=base | k6 Options

ES6 -> ES5 へトランスパイル

webpack + Babel で ES6 -> ES5 へトランスパイル/変換する方法 にて紹介した npm scripts を利用します。

k6 を高速に実行する CLI サンプル

MY_K6_TARGET_FILENAME=your_k6_es6_file.js

npm run to-es5 ./src/$MY_K6_TARGET_FILENAME

k6 run --compatibility-mode=base \
--out csv=./dist/output-$MY_K6_TARGET_FILENAME.csv \
./dist/$MY_K6_TARGET_FILENAME

以上、負荷テストツール k6 を高速に実行するために –compatibility-mode=base オプションを利用した、現場からお送りしました。