1 package Catalyst::Stats;
5 use Time::HiRes qw/gettimeofday tv_interval/;
6 use Text::SimpleTable ();
8 use Tree::Simple qw/use_weak_refs/;
9 use Tree::Simple::Visitor::FindByUID;
14 my $root = Tree::Simple->new({t => [gettimeofday]});
19 }, ref $class || $class;
23 my ($self, $enable) = @_;
25 $self->{enabled} = $enable;
31 return unless $self->{enabled};
35 $params{comment} = shift || "";
38 die "profile() requires a single comment parameter or a list of name-value pairs; found "
39 . (scalar @_) . " values: " . join(", ", @_);
43 $params{comment} ||= "";
48 my $t = [ gettimeofday ];
51 # parent is on stack; search for matching block and splice out
52 for (my $i = $#{$self->{stack}}; $i > 0; $i--) {
53 if ($self->{stack}->[$i]->getNodeValue->{action} eq $params{end}) {
54 my $node = $self->{stack}->[$i];
55 splice(@{$self->{stack}}, $i, 1);
56 # Adjust elapsed on partner node
57 my $v = $node->getNodeValue;
58 $v->{elapsed} = tv_interval($v->{t}, $t);
62 # if partner not found, fall through to treat as non-closing call
64 if ($params{parent}) {
65 # parent is explicitly defined
66 $prev = $parent = $self->_get_uid($params{parent});
69 # Find previous node, which is either previous sibling or parent, for ref time.
70 $prev = $parent = $self->{stack}->[-1] or return undef;
71 my $n = $parent->getChildCount;
72 $prev = $parent->getChild($n - 1) if $n > 0;
75 my $node = Tree::Simple->new({
76 action => $params{begin} || "",
78 elapsed => tv_interval($prev->getNodeValue->{t}, $t),
79 comment => $params{comment},
81 $node->setUID($params{uid}) if $params{uid};
83 $parent->addChild($node);
84 push(@{$self->{stack}}, $node) if $params{begin};
90 return tv_interval(shift->{tree}->getNodeValue->{t});
96 my $column_width = Catalyst::Utils::term_width() - 9 - 13;
97 my $t = Text::SimpleTable->new( [ $column_width, 'Action' ], [ 9, 'Time' ] );
99 $self->{tree}->traverse(
102 my $stat = $action->getNodeValue;
103 my @r = ( $action->getDepth,
104 ($stat->{action} || "") .
105 ($stat->{action} && $stat->{comment} ? " " : "") . ($stat->{comment} ? '- ' . $stat->{comment} : ""),
107 $stat->{action} ? 1 : 0,
109 $t->row( ( q{ } x $r[0] ) . $r[1],
110 defined $r[2] ? sprintf("%fs", $r[2]) : '??');
114 return wantarray ? @results : $t->draw;
118 my ($self, $uid) = @_;
120 my $visitor = Tree::Simple::Visitor::FindByUID->new;
121 $visitor->searchForUID($uid);
122 $self->{tree}->accept($visitor);
123 return $visitor->getResult;
129 $self->{tree}->accept( @_ );
136 my $stat = $node->getNodeValue;
138 # do we need to fake $stat->{ t } ?
139 if( $stat->{ elapsed } ) {
140 # remove the "s" from elapsed time
141 $stat->{ elapsed } =~ s{s$}{};
144 $self->{tree}->addChild( @_ );
151 # do we need to fake $stat->{ t } ?
152 if( $stat->{ elapsed } ) {
153 # remove the "s" from elapsed time
154 $stat->{ elapsed } =~ s{s$}{};
157 $self->{tree}->setNodeValue( @_ );
162 $self->{tree}->getNodeValue( @_ )->{ t };
167 $self->{tree}->traverse( @_ );
176 Catalyst::Stats - Catalyst Timing Statistics Class
182 $stats->profile($comment);
183 $stats->profile(begin => $block_name, comment =>$comment);
184 $stats->profile(end => $block_name);
185 $elapsed = $stats->elapsed;
186 $report = $stats->report;
192 This module provides the default, simple timing stats collection functionality for Catalyst.
193 If you want something different set C<< MyApp->stats_class >> in your application module,
196 __PACKAGE__->stats_class( "My::Stats" );
198 If you write your own, your stats object is expected to provide the interface described here.
200 Catalyst uses this class to report timings of component actions. You can add
201 profiling points into your own code to get deeper insight. Typical usage might
206 $c->stats->profile(begin => "mysub");
209 $c->stats->profile("starting critical bit");
212 $c->stats->profile("completed first part of critical bit");
215 $c->stats->profile("completed second part of critical bit");
218 $c->stats->profile(end => "mysub");
221 Supposing mysub was called from the action "process" inside a Catalyst
222 Controller called "service", then the reported timings for the above example
223 might look something like this:
225 .----------------------------------------------------------------+-----------.
227 +----------------------------------------------------------------+-----------+
228 | /service/process | 1.327702s |
229 | mysub | 0.555555s |
230 | - starting critical bit | 0.111111s |
231 | - completed first part of critical bit | 0.333333s |
232 | - completed second part of critical bit | 0.111000s |
234 '----------------------------------------------------------------+-----------'
236 which means mysub took 0.555555s overall, it took 0.111111s to reach the
237 critical bit, the first part of the critical bit took 0.333333s, and the second
247 $stats = Catalyst::Stats->new;
254 Enable or disable stats collection. By default, stats are enabled after object creation.
258 $stats->profile($comment);
259 $stats->profile(begin => $block_name, comment =>$comment);
260 $stats->profile(end => $block_name);
262 Marks a profiling point. These can appear in pairs, to time the block of code
263 between the begin/end pairs, or by themselves, in which case the time of
264 execution to the previous profiling point will be reported.
266 The argument may be either a single comment string or a list of name-value
267 pairs. Thus the following are equivalent:
269 $stats->profile($comment);
270 $stats->profile(comment => $comment);
272 The following key names/values may be used:
276 =item * begin => ACTION
278 Marks the beginning of a block. The value is used in the description in the
281 =item * end => ACTION
283 Marks the end of the block. The name given must match a previous 'begin'.
284 Correct nesting is recommended, although this module is tolerant of blocks that
285 are not correctly nested, and the reported timings should accurately reflect the
286 time taken to execute the block whether properly nested or not.
288 =item * comment => COMMENT
290 Comment string; use this to describe the profiling point. It is combined with
291 the block action (if any) in the timing report description field.
295 Assign a predefined unique ID. This is useful if, for whatever reason, you wish
296 to relate a profiling point to a different parent than in the natural execution
299 =item * parent => UID
301 Explicitly relate the profiling point back to the parent with the specified UID.
302 The profiling point will be ignored if the UID has not been previously defined.
306 Returns the UID of the current point in the profile tree. The UID is
307 automatically assigned if not explicitly given.
311 $elapsed = $stats->elapsed
313 Get the total elapsed time (in seconds) since the object was created.
317 print $stats->report ."\n";
318 $report = $stats->report;
319 @report = $stats->report;
321 In scalar context, generates a textual report. In array context, returns the
322 array of results where each row comprises:
324 [ depth, description, time, rollup ]
326 The depth is the calling stack level of the profiling point.
328 The description is a combination of the block name and comment.
330 The time reported for each block is the total execution time for the block, and
331 the time associated with each intermediate profiling point is the elapsed time
332 from the previous profiling point.
334 The 'rollup' flag indicates whether the reported time is the rolled up time for
335 the block, or the elapsed time from the previous profiling point.
337 =head1 COMPATABILITY METHODS
339 Some components might expect the stats object to be a regular Tree::Simple object.
340 We've added some compatability methods to handle this scenario:
358 Catalyst Contributors, see Catalyst.pm
362 This program is free software, you can redistribute it and/or modify
363 it under the same terms as Perl itself.