LoginSignup
0
2
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

[JavaScript] 処理時間を計測する方法をまとめてみた

Last updated at Posted at 2024-06-26

はじめに

特定処理の時間を計測したいときの方法をまとめてみました!

解決方法

5 種類の方法をまとめてみました!

それぞれ特徴がありますので、これらの方法の中から、目的に応じて最適なものを選んで実行時間を測定しましょう!
※ これらの方法はミリ秒で出てしまうため、出力の形によって諸々の処理は必要です。

方法 1: console.timeconsole.timeEnd を使う

console.timeconsole.timeEnd を使うと簡単に実行時間を計測できます。これらの関数はラベルを使って計測を管理します。

console.time('Execution Time');

// 諸々の処理

console.timeEnd('Execution Time');

方法 2: Date オブジェクトを使う

Date オブジェクトを使っても実行時間を計測できます。ただし、精度は以下に述べる performance.now に比べて低いです。

const start = new Date().getTime();

// 諸々の処理

const end = new Date().getTime();
const time = end - start;
console.log(`Execute time is ${time} ms`);

方法 3: performance-now を使う

Node.js の外部ライブラリである、performance-nowというライブラリを使う方法があります。

const now = require('performance-now');

const start = now();

// 諸々の処理

const end = now();
const time = end - start;
console.log(`Execute time is ${time.toFixed(3)} ms`);

方法 4:performance.now() を使う

// 実行開始の起点
const start: number = require('perf_hooks').performance.now();

// 諸々の処理

// 実行終了の起点
const end: number = require('perf_hooks').performance.now();

const time: number = Number((end - start).toFixed());
console.log(`Execute time is ${time.toFixed(4)} ms`);

方法 5: process.hrtime を使う

Node.js では、高精度の時間計測のために process.hrtime を使うことができます。

const start = process.hrtime();

// 諸々の処理

const end = process.hrtime(start);
const time = end[0] * 1000 + end[1] / 1e6;
console.log(`Execute time is ${time.toFixed(5)} ms`);
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2