Learn to Live and Live to Learn

IT(たまにビジネス)に関する記事を読んで、考えて、使ってみたことをまとめる場。

Perlでベンチマーク

Perlではその名もBenchmarkというモジュールを使うと
簡単にベンチマーク=性能比較を行えます。

まずはやってみました。

#!/usr/bin/perl -w
use strict;

use Benchmark qw/timethese cmpthese/;

my $result = timethese( 10000, {
	loop1 => sub{
		my $i = 0;
		while ( $i < 1500 ) {
			$i++;
		}
	},
	loop2 => sub{
		my $i = 0;
		while ( $i < 500 ) {
			$i++;
		}
	}
});

cmpthese $result;

実行結果はこちら。

Benchmark: timing 10000 iterations of loop1, loop2...
     loop1:  1 wallclock secs ( 0.76 usr +  0.00 sys =  0.76 CPU) @ 13157.89/s (n=10000)
     loop2:  0 wallclock secs ( 0.25 usr +  0.00 sys =  0.25 CPU) @ 40000.00/s (n=10000)
            (warning: too few iterations for a reliable count)
↓ここからがcmpthese↓
         Rate loop1 loop2
loop1 13158/s    --  -67%
loop2 40000/s  204%    --


説明させていただきます。
timethese関数

timethse( $count, {
    処理1 => sub {
    },
    処理2 => sub {
    }
});

で複数のコードを$countに指定した回数実行できます。
一つの場合はtimethisです。返り値は各関数=処理の性能情報です。
こんな感じです。

$VAR1 = {
          'loop1' => bless( [
                              1,
                              '0.74',
                              0,
                              0,
                              0,
                              10000
                            ], 'Benchmark' ),
          'loop2' => bless( [
                              0,
                              '0.25',
                              0,
                              0,
                              0,
                              10000
                            ], 'Benchmark' )
        };

timetheseで処理は指定回実行されるのですが
その結果を比較したいときはcmptheseを利用します。
cmptheseはtimetheseの結果を比較表で出力します。

comthese $timethese_result;

この書き方とこの書き方どっちが速いの?!というのを
知りたいとき手軽に使用できていいですね(^^)


参考URL
http://d.hatena.ne.jp/perlcodesample/20100509/1276960096
http://www2u.biglobe.ne.jp/MAS/perl/waza/bench.html
http://perldoc.jp/docs/modules/Benchmark-1.10/Benchmark.pod