LoginSignup
0
0

時間を計る、"Stopwatch"

Last updated at Posted at 2023-12-05

Symfony Component Advent Calendar 2023の6日目の記事です。

時間を計る、"Stopwatch"

StopWatchは、名前の通り時間を計るコンポーネントです。

インストール

composer require symfony/stopwatch

基本的な使い方

とても簡単で、Stopwatchオブジェクトを生成後、satart('{イベント名}'), stop('{イベント名}')で計測開始・終了。getEvent('{イベント名}')で計測結果であるStopwatchEventオブジェクトを取得できます。

use Symfony\Component\Stopwatch\Stopwatch;

$stopwatch = new Stopwatch();

$stopwatch->start('sample-event'); // 計測開始

// なにか処理

$stopwatch->stop('sample-event'); // 計測終了

$result = $stopwatch->getEvent('sample-event'); // 計測した内容の取得
// default/sample-event: 10.00 MiB - 78 ms

ラップ

ラップを計測したい場合も簡単で、lap('{イベント名}')を実行すれば、ラップ計測できます。

use Symfony\Component\Stopwatch\Stopwatch;

$stopwatch = new Stopwatch();

$stopwatch->start('sample-event');

foreach ($rows as $row) {
    $stopwatch->lap('sample-event');
}

$stopwatch->stop('sample-event'); // 計測終了

$result = $stopwatch->getEvent('sample-event'); // 計測した内容の取得
// default/sample-event: 10.00 MiB - 78 ms

$result->getPeriods(); // ラップ情報の取得
/*
10.00 MiB - 0 ms
10.00 MiB - 22 ms
10.00 MiB - 21 ms
10.00 MiB - 23 ms
10.00 MiB - 12 ms
*/

まとめ

今回はStopwatchでした。実は使ったことがないコンポーネントでした。デバッグ処理やバッチの起動時間を調べたい時などによく、

$start = new DateTime();
$end = new DateTime();

みたいにやってましたが、これを使えばもっと簡単に所要時間の計測ができるので、次からこっちを使っていこうと思いました!

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