0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

User Timing APIを使って処理にかかった時間をブラウザ開発者ツールで表示する方法のメモ

0
Posted at

User Timing API を使うと任意の区間の時間を計測することができます。

Vue.jsのapp.config.performanceをtrueにした場合にもこの方法が使われており
profiling.ts というところで使われています。

使い方

以下のようなコードで計測します。

async function action() {
  await doShortProcess();

  await doLongProcess();
}

短い処理doShortProcessと長い処理doLongProcess があります。
これらのそれぞれにかかった時間を計測します。

async function action() {
  window.performance.mark("短い処理:start");

  await doShortProcess();

  window.performance.mark("短い処理:end");
  window.performance.measure("短い処理", "短い処理:start", "短い処理:end");
  
  window.performance.clearMarks("短い処理:start")
  window.performance.clearMarks("短い処理:end")

  //-----------------------------------
  window.performance.mark("長い処理:start");

  await doLongProcess();

  window.performance.mark("長い処理:end");
  window.performance.measure("長い処理", "長い処理:start", "長い処理:end");
  
  window.performance.clearMarks("長い処理:start")
  window.performance.clearMarks("長い処理:end")
}

実行前、実行後 それぞれにmark メソッドを使い目印を作成します。

次にmeasure を使い2点間の時間を計測します。第1引数はメジャーのエントリー名、第2、第3引数は2点間のマークの名前です。

最後にclearMaks で2点のマークを削除します。

clearMeasuresというものもありますがVue.jsでは使われていなかったのでここでは実行していません。

計測結果

ChromeDevToolsPerformance の機能を使って計測した結果です。
quiita01.png

Timing のところに今回作成したエントリが描画されていることが確認できます。

使いやすくしてみる

このままだとコードが冗長なので まとめてみます。

計測の関数

function markStart(tag) {
  const startTag = `${tag}:start`
  window.performance.mark(startTag)
}

function markEnd(tag) {
  const endTag = `${tag}:end`
  window.performance.mark(endTag)
  
  const startTag = `${tag}:start`
  window.performance.measure(tag, startTag, endTag);
  window.performance.clearMarks(startTag)
  window.performance.clearMarks(endTag)
}

使う側

async function action() {
  markStart("短い処理");
  await doShortProcess();
  markEnd("短い処理");

  markStart("長い処理");
  await doLongProcess();
  markEnd("長い処理");
}

こうしておくと他でも使いやすくなるかと思います。

他に

今回は ブラウザの開発者ツールでの表示を紹介しましたが、他にも

といった計測結果の取得用メソッドも用意されており、自作のツールなどを作る際には必要になるかと思います。

最後に

今回はUser Timing APIと開発者ツールを組み合わせた計測方法を紹介しました。

知らないと自前で計測の仕組みを作ったりすることもあるかもしれないですが
これを知っていると視覚的にも見やすい計測結果が得られて便利だと思います。

参考

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?