7cf729a66af778f93ae59999c36d89247ba225fc
[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 ( $duration > $p ) {
30                                 my $path = "/tmp/nytprof.$id";
31                                 my $new  = "/tmp/MojoFacets.profile-$id-$duration";
32                                 rename $path, $new;
33                                 warn "profile $new $duration ", -s $new, " bytes\n";
34                         } else {
35                                 warn "profile $path $duration < $p unlink\n";
36                                 unlink $path;
37                         }
38                 }
39         );
40 }
41
42 1;