ベンチマーク
処理時間を計測する場合にはBenchmarkモジュールが便利です。
次のサンプルで500となっているところは繰り返し実行する回数の指定です。この部分に負数を指定すると、指定した数の秒数分CPUを消費するまで繰り返すようになります。
use strict;
use warnings;
use Benchmark qw(:all);
timethese (500,
{
test_a => sub {
my $a = 0;
for (my $i = 0; $i < 10000; $i++) {
$a++;
}
},
test_b => sub {
my $a = 0;
foreach (1 .. 10000) {
$a++;
}
}
}
);
実行すると以下のような結果を出力します。
Benchmark: timing 500 iterations of test_a, test_b...
test_a: 6 wallclock secs ( 2.24 usr + 0.00 sys = 2.24 CPU) @ 222.92/s (n=500)
test_b: 4 wallclock secs ( 1.62 usr + 0.00 sys = 1.62 CPU) @ 308.26/s (n=500)
timetheseの代わりにcmptheseを使うとそれぞれの実行結果の比較表を出力します。
use strict;
use warnings;
use Benchmark qw(:all);
cmpthese (500,
{
test_a => sub {
my $a = 0;
for (my $i = 0; $i < 10000; $i++) {
$a++;
}
},
test_b => sub {
my $a = 0;
foreach (1 .. 10000) {
$a++;
}
}
}
);
Rate test_a test_b
test_a 217/s -- -19%
test_b 267/s 23% --
両方出したいときはtimetheseとcmptheseを両方書きます。
use strict;
use warnings;
use Benchmark qw(:all);
cmpthese timethese (500,
{
test_a => sub {
my $a = 0;
for (my $i = 0; $i < 10000; $i++) {
$a++;
}
},
test_b => sub {
my $a = 0;
foreach (1 .. 10000) {
$a++;
}
}
}
);
Benchmark: timing 500 iterations of test_a, test_b...
test_a: 6 wallclock secs ( 2.26 usr + 0.00 sys = 2.26 CPU) @ 220.95/s (n=500)
test_b: 4 wallclock secs ( 2.05 usr + 0.00 sys = 2.05 CPU) @ 243.55/s (n=500)
Rate test_a test_b
test_a 221/s -- -9%
test_b 244/s 10% --
関連項目
・times関数・プロファイラ
・CGIのプロファイルを取得
・メトリクスの取得
