1 package Catalyst::Stats;
5 use Time::HiRes qw/gettimeofday tv_interval/;
6 use Text::SimpleTable ();
7 use Tree::Simple qw/use_weak_refs/;
8 use Tree::Simple::Visitor::FindByUID;
13 my $root = Tree::Simple->new({t => [gettimeofday]});
18 }, ref $class || $class;
22 my ($self, $enable) = @_;
24 $self->{enabled} = $enable;
30 return unless $self->{enabled};
34 $params{comment} = shift || "";
37 die "profile() requires a single comment parameter or a list of name-value pairs; found "
38 . (scalar @_) . " values: " . join(", ", @_);
42 $params{comment} ||= "";
47 my $t = [ gettimeofday ];
50 # parent is on stack; search for matching block and splice out
51 for (my $i = $#{$self->{stack}}; $i > 0; $i--) {
52 if ($self->{stack}->[$i]->getNodeValue->{action} eq $params{end}) {
53 my $node = $self->{stack}->[$i];
54 splice(@{$self->{stack}}, $i, 1);
55 # Adjust elapsed on partner node
56 my $v = $node->getNodeValue;
57 $v->{elapsed} = tv_interval($v->{t}, $t);
61 # if partner not found, fall through to treat as non-closing call
63 if ($params{parent}) {
64 # parent is explicitly defined
65 $prev = $parent = $self->_get_uid($params{parent});
68 # Find previous node, which is either previous sibling or parent, for ref time.
69 $prev = $parent = $self->{stack}->[-1] or return undef;
70 my $n = $parent->getChildCount;
71 $prev = $parent->getChild($n - 1) if $n > 0;
74 my $node = Tree::Simple->new({
75 action => $params{begin} || "",
77 elapsed => tv_interval($prev->getNodeValue->{t}, $t),
78 comment => $params{comment},
80 $node->setUID($params{uid}) if $params{uid};
82 $parent->addChild($node);
83 push(@{$self->{stack}}, $node) if $params{begin};
89 return tv_interval(shift->{tree}->getNodeValue->{t});
95 # close any remaining open nodes
96 for (my $i = $#{$self->{stack}}; $i > 0; $i--) {
97 $self->profile(end => $self->{stack}->[$i]->getNodeValue->{action});
100 my $t = Text::SimpleTable->new( [ 62, 'Action' ], [ 9, 'Time' ] );
102 $self->{tree}->traverse(
105 my $stat = $action->getNodeValue;
106 my @r = ( $action->getDepth,
107 ($stat->{action} || "") .
108 ($stat->{action} && $stat->{comment} ? " " : "") . ($stat->{comment} ? '- ' . $stat->{comment} : ""),
110 $stat->{action} ? 1 : 0,
112 $t->row( ( q{ } x $r[0] ) . $r[1],
113 defined $r[2] ? sprintf("%fs", $r[2]) : '??');
117 return wantarray ? @results : $t->draw;
121 my ($self, $uid) = @_;
123 my $visitor = Tree::Simple::Visitor::FindByUID->new;
124 $visitor->searchForUID($uid);
125 $self->{tree}->accept($visitor);
126 return $visitor->getResult;
132 $self->{tree}->accept( @_ );
139 my $stat = $node->getNodeValue;
141 # do we need to fake $stat->{ t } ?
142 if( $stat->{ elapsed } ) {
143 # remove the "s" from elapsed time
144 $stat->{ elapsed } =~ s{s$}{};
147 $self->{tree}->addChild( @_ );
154 # do we need to fake $stat->{ t } ?
155 if( $stat->{ elapsed } ) {
156 # remove the "s" from elapsed time
157 $stat->{ elapsed } =~ s{s$}{};
160 $self->{tree}->setNodeValue( @_ );
165 $self->{tree}->getNodeValue( @_ )->{ t };
170 $self->{tree}->traverse( @_ );
179 Catalyst::Stats - Catalyst Timing Statistics Class
185 $stats->profile($comment);
186 $stats->profile(begin => $block_name, comment =>$comment);
187 $stats->profile(end => $block_name);
188 $elapsed = $stats->elapsed;
189 $report = $stats->report;
195 This module provides the default, simple timing stats collection functionality for Catalyst.
196 If you want something different set C<< MyApp->stats_class >> in your application module,
199 __PACKAGE__->stats_class( "My::Stats" );
201 If you write your own, your stats object is expected to provide the interface described here.
203 Catalyst uses this class to report timings of component actions. You can add
204 profiling points into your own code to get deeper insight. Typical usage might
209 $c->stats->profile(begin => "mysub");
212 $c->stats->profile("starting critical bit");
215 $c->stats->profile("completed first part of critical bit");
218 $c->stats->profile("completed second part of critical bit");
221 $c->stats->profile(end => "mysub");
224 Supposing mysub was called from the action "process" inside a Catalyst
225 Controller called "service", then the reported timings for the above example
226 might look something like this:
228 .----------------------------------------------------------------+-----------.
230 +----------------------------------------------------------------+-----------+
231 | /service/process | 1.327702s |
232 | mysub | 0.555555s |
233 | - starting critical bit | 0.111111s |
234 | - completed first part of critical bit | 0.333333s |
235 | - completed second part of critical bit | 0.111000s |
237 '----------------------------------------------------------------+-----------'
239 which means mysub took 0.555555s overall, it took 0.111111s to reach the
240 critical bit, the first part of the critical bit took 0.333333s, and the second
250 $stats = Catalyst::Stats->new;
257 Enable or disable stats collection. By default, stats are enabled after object creation.
261 $stats->profile($comment);
262 $stats->profile(begin => $block_name, comment =>$comment);
263 $stats->profile(end => $block_name);
265 Marks a profiling point. These can appear in pairs, to time the block of code
266 between the begin/end pairs, or by themselves, in which case the time of
267 execution to the previous profiling point will be reported.
269 The argument may be either a single comment string or a list of name-value
270 pairs. Thus the following are equivalent:
272 $stats->profile($comment);
273 $stats->profile(comment => $comment);
275 The following key names/values may be used:
279 =item * begin => ACTION
281 Marks the beginning of a block. The value is used in the description in the
284 =item * end => ACTION
286 Marks the end of the block. The name given must match a previous 'begin'.
287 Correct nesting is recommended, although this module is tolerant of blocks that
288 are not correctly nested, and the reported timings should accurately reflect the
289 time taken to execute the block whether properly nested or not.
291 =item * comment => COMMENT
293 Comment string; use this to describe the profiling point. It is combined with
294 the block action (if any) in the timing report description field.
298 Assign a predefined unique ID. This is useful if, for whatever reason, you wish
299 to relate a profiling point to a different parent than in the natural execution
302 =item * parent => UID
304 Explicitly relate the profiling point back to the parent with the specified UID.
305 The profiling point will be ignored if the UID has not been previously defined.
309 Returns the UID of the current point in the profile tree. The UID is
310 automatically assigned if not explicitly given.
314 $elapsed = $stats->elapsed
316 Get the total elapsed time (in seconds) since the object was created.
320 print $stats->report ."\n";
321 $report = $stats->report;
322 @report = $stats->report;
324 In scalar context, generates a textual report. In array context, returns the
325 array of results where each row comprises:
327 [ depth, description, time, rollup ]
329 The depth is the calling stack level of the profiling point.
331 The description is a combination of the block name and comment.
333 The time reported for each block is the total execution time for the block, and
334 the time associated with each intermediate profiling point is the elapsed time
335 from the previous profiling point.
337 The 'rollup' flag indicates whether the reported time is the rolled up time for
338 the block, or the elapsed time from the previous profiling point.
340 =head1 COMPATABILITY METHODS
342 Some components might expect the stats object to be a regular Tree::Simple object.
343 We've added some compatability methods to handle this scenario:
361 Catalyst Contributors, see Catalyst.pm
365 This program is free software, you can redistribute it and/or modify
366 it under the same terms as Perl itself.