LoginSignup
8
2

More than 3 years have passed since last update.

Node: 関数の実行速度を計測する(Performance Timing API使用)

Posted at

Node.jsのPerformance Timing APIを使って、関数の実行速度を計測する方法を紹介する。

Performance Timing APIは高解像度パフォーマンスメトリクスの収集をサポートするAPI。

基本的な使い方

const {performance, PerformanceObserver} = require('perf_hooks');

// 測定対象の関数
function someFunction() {
    console.log('hello world');
}

// 測定対象の関数を測定可能にする
const wrapped = performance.timerify(someFunction);

// 測定結果を随時処理するオブザーバーを定義する
const obs = new PerformanceObserver((list) => {
    console.log(list.getEntries()[0].duration);
    obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

// 測定を開始
wrapped();

測定しやすくする関数を作る

Performance Timing APIをそのまま使ってもいいが、測定しやすくなるよう関数化しておくといい。

const {PerformanceObserver, performance} = require('perf_hooks')

const measure = (fn, loop = 100) => {
    return new Promise(resolve => {
        const obs = new PerformanceObserver((items) => {
            const durations = []
            for (const perf of items.getEntriesByType('function')) {
                durations.push(perf.duration)
            }
            const average = durations.reduce((a, b) => a + b, 0) / durations.length // 平均値の計算
            obs.disconnect()
            resolve(average)
        })
        obs.observe({entryTypes: ['function'], buffered: true})
        const f = performance.timerify(fn)

        for (let i = 0; i < loop; i++) {
            f()
        }
    })
}

測定する:

(async () => {
    function fib(n) {
        return n < 2 ? n : fib(n - 2) + fib(n - 1)
    }

    let seconds = await measure(() => {
        fib(30)
    })
    console.log(seconds)
})()
8
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
8
2