nytprof.disabled added
[MojoFacets.git] / lib / MojoFacets / Plugin / NYTProf.pm
1 package MojoFacets::Plugin::NYTProf;
2
3 use Devel::NYTProf;
4 use Time::HiRes ();
5
6 sub register {
7         my ($self, $app) = @_;
8
9         # Start timer
10         $app->plugins->add_hook(
11                 before_dispatch => sub {
12                         my ($self, $c) = @_;
13                         return unless $ENV{PROFILE};
14                         my $id = Time::HiRes::gettimeofday();
15                         $c->stash('nytprof.id' => $id);
16                         my $path = "/tmp/nytprof.$id";
17                         DB::enable_profile($path);
18                 }
19         );
20
21         # End timer
22         $app->plugins->add_hook(
23                 after_dispatch => sub {
24                         my ($self, $c) = @_;
25                         my $p = $ENV{PROFILE} || return;
26                         DB::disable_profile();
27                         return unless my $id = $c->stash('nytprof.id');
28                         my $duration = Time::HiRes::gettimeofday() - $id;
29                         if ( $c->stash('nytprof.disabled') ) {
30                                 warn "profile disabled";
31                                 unlink $path;
32                         } elsif ( $duration > $p ) {
33                                 my $path = "/tmp/nytprof.$id";
34                                 my $new  = "/tmp/MojoFacets.profile.$id-$duration";
35                                 rename $path, $new;
36                                 warn "profile $new $duration ", -s $new, " bytes\n";
37                         } else {
38                                 warn "profile $path $duration < $p unlink\n";
39                                 unlink $path;
40                         }
41                 }
42         );
43 }
44
45 1;