| 1 | package CGI::Application::Plugin::DevPopup::Timing; | ||
| 2 | { | ||
| 3 | $CGI::Application::Plugin::DevPopup::Timing::VERSION = '1.08'; | ||
| 4 | } | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use base qw/Exporter/; | ||
| 8 | use Time::HiRes qw/gettimeofday tv_interval/; | ||
| 9 | my $start = [gettimeofday]; | ||
| 10 | |||
| 11 | sub import | ||
| 12 | { | ||
| 13 | my $c = scalar caller; | ||
| 14 | $c->add_callback( 'devpopup_report', \&_timer_report ); | ||
| 15 | $c->new_hook('devpopup_addtiming'); | ||
| 16 | $c->add_callback( 'devpopup_addtiming', \&_add_time ); | ||
| 17 | foreach my $stage (qw/ init prerun load_tmpl /) | ||
| 18 | { | ||
| 19 | $c->add_callback( $stage, sub { _add_time( shift(), $stage, @_ ) } ); | ||
| 20 | } | ||
| 21 | goto &Exporter::import; | ||
| 22 | } | ||
| 23 | |||
| 24 | sub _timer_report | ||
| 25 | { | ||
| 26 | my $app = shift; | ||
| 27 | |||
| 28 | my $self = _new_or_self($app); | ||
| 29 | unshift @$self, { dec => 'start', tod => $start }; | ||
| 30 | _add_time( $app, 'postrun' ); | ||
| 31 | $app->devpopup->add_report( | ||
| 32 | title => 'Timings', | ||
| 33 | summary => 'Total runtime: ' . tv_interval( $self->[1]{tod}, $self->[-1]{tod} ) . ' sec.', | ||
| 34 | report => '<style> | ||
| 35 | th { text-align:left; border-bottom:solid 1px black; } | ||
| 36 | </style>' . | ||
| 37 | 'Application started at: ' . scalar( gmtime( $start->[0] ) ) . ' GMT<br/>' . | ||
| 38 | '<table width="100%"><tr><th>From</th><th>To</th><th>Time taken</th></tr>' . | ||
| 39 | join( | ||
| 40 | $/, | ||
| 41 | map { | ||
| 42 | my $time = tv_interval( $self->[$_]{tod}, $self->[ $_ + 1 ]{tod} ); | ||
| 43 | "<tr><td>$self->[$_]{desc}</td><td>$self->[ $_ + 1 ]{desc}</td><td>$time sec.</td></tr>" | ||
| 44 | } ( 1 .. $#$self - 1 ) | ||
| 45 | ) | ||
| 46 | . '</table>' | ||
| 47 | ); | ||
| 48 | } | ||
| 49 | |||
| 50 | sub _add_time | ||
| 51 | { | ||
| 52 | my $app = shift; | ||
| 53 | my $stage = shift; | ||
| 54 | $stage .= '(' . $_[-1] . ')' if $stage =~ /load_tmpl/; | ||
| 55 | |||
| 56 | my $self = _new_or_self($app); | ||
| 57 | push @$self, { desc => $stage, tod => [gettimeofday] }; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub _new_or_self | ||
| 61 | { | ||
| 62 | my $app = shift; | ||
| 63 | my $self = $app->param('__CAP_DEVPOPUP_TIMER'); | ||
| 64 | unless ($self) | ||
| 65 | { | ||
| 66 | $self = bless [], __PACKAGE__; | ||
| 67 | $app->param( '__CAP_DEVPOPUP_TIMER' => $self ); | ||
| 68 | } | ||
| 69 | return $self; | ||
| 70 | } | ||
| 71 | |||
| 72 | 1; # End of CGI::Application::Plugin::DevPopup::Timing | ||
| 73 | |||
| 74 | __END__ |