Smart::Intervalというモジュールを書いてみた

Smart::Commentsを参考に簡易プロファイラみたいなのを書いてみた。
モジュールっぽいのは初めてかも。

Smart::Interval

package Smart::Interval; 
use strict;
use utf8;
use Time::HiRes qw/gettimeofday tv_interval/;
use Filter::Simple;
use Clone qw(clone);
my $hws     = qr/[^\S\n]/;

my $st = {
    pref => "",
    time => "",
};
my $ed = clone($st);

FILTER {
    shift;        # Don't need the package name
    s/\r\n/\n/g;  # Handle win32 line endings

    my $intro = qr/#{3,}/;

    s{ ^ $hws* $intro $hws* (.*) }
     {Smart::Interval::_Dump(q{$1});}gmx;
};

sub _Dump {
    my $pref = shift;
    my $flg;
    if($ed->{pref}){
        $st = clone($ed);
        $flg = 1;
    }else{
        $st->{pref} = $pref;
        $st->{time} = [gettimeofday];
    }
    $ed->{pref} = $pref;
    $ed->{time} = [gettimeofday];
    printf "  |  (%.8f sec)\n", tv_interval($st->{time}, $ed->{time}) if $flg;
    print "### Smart::Interval ", $ed->{pref}, "\n";
    #print $ed->{pref}, "\n";
}

1;

使い方

Smart::Commentsみたいに三連#を判別して、コメントからコメントまでの間の秒数を表示します。

サンプルコード
use strict;
use Time::HiRes qw( sleep );
use Smart::Interval;

### Smart1----
sleep (0.009);
### Smart2----
sleep (2.41);
### Smart3----
sleep (1.1);
### Smart4----
sleep (0.381);
### Smart5----
実行結果
### Smart::Interval smart1----
  |  (0.00909400 sec)
### Smart::Interval smart2----
  |  (2.41006600 sec)
### Smart::Interval smart3----
  |  (1.10019600 sec)
### Smart::Interval smart4----
  |  (0.38113200 sec)
### Smart::Interval smart5----

もちろんSmart::Commentsと同様に、
useをコメントアウトするだけで表示しなくなります。

雑記

単一スクリプト以外で使うといろいろとダメだと思います。
あとフラグでprintできる内容とか変えれるようにしようと考えてます。
あとソースフィルタおもしろいですね!