15
20

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 5 years have passed since last update.

Perlでミリ秒単位の時間計測を行う(Time::HiResを利用)

Last updated at Posted at 2014-04-14

Perlでミリ秒以下の計測を行うためには Time::HiRes モジュールを利用します。

以下にサンプルを示します。

use strict;
use warnings;
use utf8;
use feature qw( say );
binmode(STDOUT, ":utf8");

use Time::HiRes qw( usleep gettimeofday tv_interval );

# 現在時刻を取得([currentsec, currentmicrosec]の構造になっている)
my $t0 = [gettimeofday];

# 200 * 1000マイクロ秒 → 200ミリ秒のsleep
usleep(200 * 1000);

#  浮動小数点数で経過時間を取得(このサンプルだと0.20xxxx秒程)
my $elapsed = tv_interval($t0);

say int($elapsed * 1000), "ミリ秒";

お手軽にワンライナーで実験するなら次のようになります。

perl -MTime::HiRes=usleep,gettimeofday,tv_interval -E 'my $t0 = [gettimeofday]; usleep(200 * 1000); say int(tv_interval($t0) * 1000)'

特定の関数の実行時間を測りたいときはミリ秒の精度が欲しいため、筆者は上記の方法でよく計測しています。

15
20
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
15
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?