LoginSignup
8

More than 3 years have passed since last update.

Node.jsの、コードの実行時間を計測

Last updated at Posted at 2019-05-10

 alt
Node.jsで書かれたコードのパフォーマンスを測定する必要があった。

その際、コードの実行速度を計測するのに良さげな方法を見つけたので、共有する。

setTimeoutで、コードを遅延させ、実行速度を計測してみる。

まずは、一般的なDateを使った方法から!

var start = new Date()
var simulateTime = 1000

setTimeout(function(argument) {
  // execution time simulated with setTimeout function
  var end = new Date() - start
  console.info('Execution time: %dms', end)
}, simulateTime)

結果は

Execution time: 1002ms

と表示される
一般的にはこれで十分だ。なぜなら、jsでコードを書く場合msまで計測できればパフォーマンスの計測としては必要十分だからだ。

しかし、エンジニアには時にもうちょっと精度よくコードのパフォーマンスを計測したい時がある。

そのための仕組みがnodeには標準装備されていて、 process.hrtime()という
これは、[seconds, nanoseconds] というArrayを返す関数だ。
使い方は、ちょっと変わっていて、計測開始の、process.hrtime()の返り値を、計測終了のprocess.hrtime()の引数として渡してあげる必要がある。

var start = new Date()
var hrstart = process.hrtime()
var simulateTime = 5

setTimeout(function(argument) {
  // execution time simulated with setTimeout function
  var end = new Date() - start,
    hrend = process.hrtime(hrstart)

  console.info('Execution time: %dms', end)
  console.info('Execution time (hr): %ds %dms', hrend[0], hrend[1] / 1000000)
}, simulateTime)

結果は、以下のように表示される。

Execution time: 7ms
Execution time (hr): 0s 6.858948ms

Execution time: 6ms
Execution time (hr): 0s 6.285195ms

まあ、標準で、こういう関数「使える」関数が用意されてるのが、nodeが世界中で使われる理由の一つなんだと思いました。
以上酔っ払いからのレポートでした

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
8