node.js performance.now使用時に「ReferenceError: performance is not defined」が発生した場合の対処

node.jsでperformance.now使用時に「ReferenceError: performance is not defined」が発生した場合の対処法を記述してます。nodeのバージョンは14.15.1となります。
環境
- OS Ubuntu 20.10
- node V14.15.1
- npm 6.14.9
エラー内容
以下のコードで発生
// 計測開始
const start = performance.now();
// 繰り返し実行
for (let i = 0; i < 10; ++i) {
func();
}
// 計測終了
const end = performance.now();
エラー全文
const start = performance.now();
^
ReferenceError: performance is not defined
原因
node.jsでは、「perf_hooks」モジュールをrequireする必要がある
対処法
requireします。
const performance = require('perf_hooks').performance;
以下でもOK
const { performance } = require('perf_hooks');
また、nodeでベンチマークを計測するなら、benchmarkも使用できます。
npm install benchmark
-
前の記事
javascript 全角文字は2文字で半角文字は1文字としてカウントする 2020.12.21
-
次の記事
ubuntu20.10 Bleachbitをインストールして不要なファイルを削除する 2020.12.22
コメントを書く