1 package Catalyst::Stats;
4 use Time::HiRes qw/gettimeofday tv_interval/;
5 use Text::SimpleTable ();
6 use Tree::Simple qw/use_weak_refs/;
7 use Tree::Simple::Visitor::FindByUID;
9 has enable => (is => 'rw', required => 1, default => sub{ 1 });
13 default => sub{ Tree::Simple->new({t => [gettimeofday]}) }
19 default => sub { [ shift->tree ] }
25 return unless $self->enable;
29 $params{comment} = shift || "";
32 die "profile() requires a single comment parameter or a list of name-value pairs; found "
33 . (scalar @_) . " values: " . join(", ", @_);
37 $params{comment} ||= "";
42 my $t = [ gettimeofday ];
43 my $stack = $self->stack;
46 # parent is on stack; search for matching block and splice out
47 for (my $i = $#{$stack}; $i > 0; $i--) {
48 if ($stack->[$i]->getNodeValue->{action} eq $params{end}) {
49 my ($node) = splice(@{$stack}, $i, 1);
50 # Adjust elapsed on partner node
51 my $v = $node->getNodeValue;
52 $v->{elapsed} = tv_interval($v->{t}, $t);
56 # if partner not found, fall through to treat as non-closing call
58 if ($params{parent}) {
59 # parent is explicitly defined
60 $prev = $parent = $self->_get_uid($params{parent});
63 # Find previous node, which is either previous sibling or parent, for ref time.
64 $prev = $parent = $stack->[-1] or return undef;
65 my $n = $parent->getChildCount;
66 $prev = $parent->getChild($n - 1) if $n > 0;
69 my $node = Tree::Simple->new({
70 action => $params{begin} || "",
72 elapsed => tv_interval($prev->getNodeValue->{t}, $t),
73 comment => $params{comment},
75 $node->setUID($params{uid}) if $params{uid};
77 $parent->addChild($node);
78 push(@{$stack}, $node) if $params{begin};
84 return tv_interval(shift->{tree}->getNodeValue->{t});
90 # close any remaining open nodes
91 map { $self->profile(end => $_->getNodeValue->{action}) }
92 (reverse @{ $self->stack })[1 .. $#{$self->stack}];
94 my $t = Text::SimpleTable->new( [ 62, 'Action' ], [ 9, 'Time' ] );
96 $self->tree->traverse(
99 my $stat = $action->getNodeValue;
100 my @r = ( $action->getDepth,
101 ($stat->{action} || "") .
102 ($stat->{action} && $stat->{comment} ? " " : "") . ($stat->{comment} ? '- ' . $stat->{comment} : ""),
104 $stat->{action} ? 1 : 0,
106 # Trim down any times >= 10 to avoid ugly Text::Simple line wrapping
107 my $elapsed = substr(sprintf("%f", $stat->{elapsed}), 0, 8) . "s";
108 $t->row( ( q{ } x $r[0] ) . $r[1],
109 defined $r[2] ? $elapsed : '??');
113 return wantarray ? @results : $t->draw;
117 my ($self, $uid) = @_;
119 my $visitor = Tree::Simple::Visitor::FindByUID->new;
120 $visitor->searchForUID($uid);
121 $self->tree->accept($visitor);
122 return $visitor->getResult;
127 $self->{tree}->accept( @_ );
134 my $stat = $node->getNodeValue;
136 # do we need to fake $stat->{ t } ?
137 if( $stat->{ elapsed } ) {
138 # remove the "s" from elapsed time
139 $stat->{ elapsed } =~ s{s$}{};
142 $self->{tree}->addChild( @_ );
149 # do we need to fake $stat->{ t } ?
150 if( $stat->{ elapsed } ) {
151 # remove the "s" from elapsed time
152 $stat->{ elapsed } =~ s{s$}{};
155 $self->{tree}->setNodeValue( @_ );
160 $self->{tree}->getNodeValue( @_ )->{ t };
165 $self->{tree}->traverse( @_ );
169 __PACKAGE__->meta->make_immutable();
177 Catalyst::Stats - Catalyst Timing Statistics Class
183 $stats->profile($comment);
184 $stats->profile(begin => $block_name, comment =>$comment);
185 $stats->profile(end => $block_name);
186 $elapsed = $stats->elapsed;
187 $report = $stats->report;
193 This module provides the default, simple timing stats collection functionality for Catalyst.
194 If you want something different set C<< MyApp->stats_class >> in your application module,
197 __PACKAGE__->stats_class( "My::Stats" );
199 If you write your own, your stats object is expected to provide the interface described here.
201 Catalyst uses this class to report timings of component actions. You can add
202 profiling points into your own code to get deeper insight. Typical usage might
207 $c->stats->profile(begin => "mysub");
210 $c->stats->profile("starting critical bit");
213 $c->stats->profile("completed first part of critical bit");
216 $c->stats->profile("completed second part of critical bit");
219 $c->stats->profile(end => "mysub");
222 Supposing mysub was called from the action "process" inside a Catalyst
223 Controller called "service", then the reported timings for the above example
224 might look something like this:
226 .----------------------------------------------------------------+-----------.
228 +----------------------------------------------------------------+-----------+
229 | /service/process | 1.327702s |
230 | mysub | 0.555555s |
231 | - starting critical bit | 0.111111s |
232 | - completed first part of critical bit | 0.333333s |
233 | - completed second part of critical bit | 0.111000s |
235 '----------------------------------------------------------------+-----------'
237 which means mysub took 0.555555s overall, it took 0.111111s to reach the
238 critical bit, the first part of the critical bit took 0.333333s, and the second
248 $stats = Catalyst::Stats->new;
255 Enable or disable stats collection. By default, stats are enabled after object creation.
259 $stats->profile($comment);
260 $stats->profile(begin => $block_name, comment =>$comment);
261 $stats->profile(end => $block_name);
263 Marks a profiling point. These can appear in pairs, to time the block of code
264 between the begin/end pairs, or by themselves, in which case the time of
265 execution to the previous profiling point will be reported.
267 The argument may be either a single comment string or a list of name-value
268 pairs. Thus the following are equivalent:
270 $stats->profile($comment);
271 $stats->profile(comment => $comment);
273 The following key names/values may be used:
277 =item * begin => ACTION
279 Marks the beginning of a block. The value is used in the description in the
282 =item * end => ACTION
284 Marks the end of the block. The name given must match a previous 'begin'.
285 Correct nesting is recommended, although this module is tolerant of blocks that
286 are not correctly nested, and the reported timings should accurately reflect the
287 time taken to execute the block whether properly nested or not.
289 =item * comment => COMMENT
291 Comment string; use this to describe the profiling point. It is combined with
292 the block action (if any) in the timing report description field.
296 Assign a predefined unique ID. This is useful if, for whatever reason, you wish
297 to relate a profiling point to a different parent than in the natural execution
300 =item * parent => UID
302 Explicitly relate the profiling point back to the parent with the specified UID.
303 The profiling point will be ignored if the UID has not been previously defined.
307 Returns the UID of the current point in the profile tree. The UID is
308 automatically assigned if not explicitly given.
312 $elapsed = $stats->elapsed
314 Get the total elapsed time (in seconds) since the object was created.
318 print $stats->report ."\n";
319 $report = $stats->report;
320 @report = $stats->report;
322 In scalar context, generates a textual report. In array context, returns the
323 array of results where each row comprises:
325 [ depth, description, time, rollup ]
327 The depth is the calling stack level of the profiling point.
329 The description is a combination of the block name and comment.
331 The time reported for each block is the total execution time for the block, and
332 the time associated with each intermediate profiling point is the elapsed time
333 from the previous profiling point.
335 The 'rollup' flag indicates whether the reported time is the rolled up time for
336 the block, or the elapsed time from the previous profiling point.
338 =head1 COMPATABILITY METHODS
340 Some components might expect the stats object to be a regular Tree::Simple object.
341 We've added some compatability methods to handle this scenario:
359 Catalyst Contributors, see Catalyst.pm
363 This program is free software, you can redistribute it and/or modify
364 it under the same terms as Perl itself.
368 __PACKAGE__->meta->make_immutable;