m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Perlでロジックのベンチマーク

スピードアップの復習

速度ロジックを見ただけで組んでいないのでちょっと復習

必要なもの

Benchmarkというものの「timethese」と「cmpthese」が必要

サンプル

#!/usr/bin/env perl

use strict;
use warnings;

use Benchmark qw( timethese cmpthese );

# ロジック1
my $sample1 = sub {

    my $result = "";
    my $aaa = 10;

    if($aaa == 10){
        $result = "111";
    }

    if($result eq "111"){
        $result = "ok";
    }else{
        $result = "ng";
    }

    return $result;

};

# ロジック2
my $sample2 = sub {

    my $aaa = 10;

    return ($aaa == 10) ? "ok" : "ng";

};

# サンプル
cmpthese timethese(10000, {
    test1 => $sample1,
    test2 => $sample2
});

cmpthese timethese(100000, {
    test1 => $sample1,
    test2 => $sample2
});

cmpthese timethese(1000000, {
    test1 => $sample1,
    test2 => $sample2
});

結果

1万回でベンチマーク
[root@localhost benchmark]# perl sample01.pl
Benchmark: timing 10000 iterations of test1, test2...
     test1:  0 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
            (warning: too few iterations for a reliable count)
     test2:  0 wallclock secs ( 0.00 usr +  0.00 sys =  0.00 CPU)
            (warning: too few iterations for a reliable count)
                        Rate test2 test1
test2 10000000000000000000/s    --    0%
test1 10000000000000000000/s    0%    --
[root@localhost benchmark]#
10万回でベンチマーク
[root@localhost benchmark]#
Benchmark: timing 100000 iterations of test1, test2...
     test1:  0 wallclock secs ( 0.06 usr +  0.00 sys =  0.06 CPU) @ 1666666.67/s (n=100000)
            (warning: too few iterations for a reliable count)
     test2:  1 wallclock secs ( 0.02 usr +  0.00 sys =  0.02 CPU) @ 5000000.00/s (n=100000)
            (warning: too few iterations for a reliable count)
           Rate test1 test2
test1 1666667/s    --  -67%
test2 5000000/s  200%    --
[root@localhost benchmark]#
100万回でベンチマーク
[root@localhost benchmark]#
Benchmark: timing 1000000 iterations of test1, test2...
     test1:  1 wallclock secs ( 0.59 usr +  0.00 sys =  0.59 CPU) @ 1694915.25/s (n=1000000)
     test2:  0 wallclock secs ( 0.16 usr +  0.00 sys =  0.16 CPU) @ 6250000.00/s (n=1000000)
            (warning: too few iterations for a reliable count)
           Rate test1 test2
test1 1694915/s    --  -73%
test2 6250000/s  269%    --
[root@localhost benchmark]#

「timethese」と「cmpthese」

timethese

ロジックのベンチメークの結果を返す

cmpthese

timetheseによるベンチマークの結果を返却



まとめ

ロジックの処理がシンプルの場合は回数を多めにしないと速いかの区別がつかない
あと、数回実行した結果、時間にズレがあるようでした1回のベンチマークではなく
数回に分けてベンチマークを取って計測することが重要ですね