File Coverage

blib/lib/Catalyst/Stats.pm
Criterion Covered Total %
statement 86 87 98.8
branch 35 40 87.5
condition 10 11 90.9
subroutine 16 16 100.0
pod 7 7 100.0
total 154 161 95.6


line stmt bran cond sub pod time code
1              
2             use Moose;
3 155     155   75793 use Time::HiRes qw/gettimeofday tv_interval/;
  155         470107  
  155         1294  
4 155     155   1121038 use Text::SimpleTable ();
  155         233315  
  155         5052  
5 155     155   41656 use Catalyst::Utils;
  155         4899  
  155         5398  
6 155     155   7773 use Tree::Simple qw/use_weak_refs/;
  155         2426  
  155         9500  
7 155     155   2892 use Tree::Simple::Visitor::FindByUID;
  155         4540  
  155         1606  
8 155     155   12891  
  155         2630  
  155         7978  
9             use namespace::clean -except => 'meta';
10 155     155   3047  
  155         2638  
  155         3828  
11             has enable => (is => 'rw', required => 1, default => sub{ 1 });
12             has tree => (
13             is => 'ro',
14             required => 1,
15             default => sub{ Tree::Simple->new({t => [gettimeofday]}) },
16             handles => [qw/ accept traverse /],
17             );
18             has stack => (
19             is => 'ro',
20             required => 1,
21             lazy => 1,
22             default => sub { [ shift->tree ] }
23             );
24              
25             my $self = shift;
26              
27 76     76 1 1151 return unless $self->enable;
28              
29 76 100       2096 my %params;
30             if (@_ <= 1) {
31 75         137 $params{comment} = shift || "";
32 75 100       293 }
    50          
33 4   50     17 elsif (@_ % 2 != 0) {
34             die "profile() requires a single comment parameter or a list of name-value pairs; found "
35             . (scalar @_) . " values: " . join(", ", @_);
36 0         0 }
37             else {
38             (%params) = @_;
39             $params{comment} ||= "";
40 71         256 }
41 71   100     315  
42             my $parent;
43             my $prev;
44 75         137 my $t = [ gettimeofday ];
45             my $stack = $self->stack;
46 75         291  
47 75         1949 if ($params{end}) {
48             # parent is on stack; search for matching block and splice out
49 75 100       185 for (my $i = $#{$stack}; $i > 0; $i--) {
50             if ($stack->[$i]->getNodeValue->{action} eq $params{end}) {
51 33         70 my ($node) = splice(@{$stack}, $i, 1);
  33         124  
52 37 100       148 # Adjust elapsed on partner node
53 33         159 my $v = $node->getNodeValue;
  33         90  
54             $v->{elapsed} = tv_interval($v->{t}, $t);
55 33         83 return $node->getUID;
56 33         181 }
57 33         470 }
58             # if partner not found, fall through to treat as non-closing call
59             }
60             if ($params{parent}) {
61             # parent is explicitly defined
62 42 100       122 $prev = $parent = $self->_get_uid($params{parent});
63             }
64 5         17 if (!$parent) {
65             # Find previous node, which is either previous sibling or parent, for ref time.
66 42 100       218 $prev = $parent = $stack->[-1] or return undef;
67             my $n = $parent->getChildCount;
68 37 50       119 $prev = $parent->getChild($n - 1) if $n > 0;
69 37         173 }
70 37 100       294  
71             my $node = Tree::Simple->new({
72             action => $params{begin} || "",
73             t => $t,
74             elapsed => tv_interval($prev->getNodeValue->{t}, $t),
75             comment => $params{comment},
76             });
77             $node->setUID($params{uid}) if $params{uid};
78 42   100     270  
79 42 100       2486 $parent->addChild($node);
80             push(@{$stack}, $node) if $params{begin};
81 42         296  
82 42 100       4482 return $node->getUID;
  34         94  
83             }
84 42         135  
85             return @{ shift->{tree}->getNodeValue->{t} };
86             }
87              
88 1     1 1 764 return tv_interval(shift->{tree}->getNodeValue->{t});
  1         6  
89             }
90              
91             my $self = shift;
92 16     16 1 2725  
93             my $t;
94             my @results;
95              
96 16     16 1 55 if (!wantarray) {
97             $t = Text::SimpleTable->new(
98 16         43 [ Catalyst::Utils::term_width() - 9 - 13, 'Action' ],
99             [ 9, 'Time' ],
100             );
101 16 100       88 }
102 15         92  
103             $self->traverse(sub {
104             my $action = shift;
105             my $stat = $action->getNodeValue;
106             my @r = ( $action->getDepth,
107             ($stat->{action} || "") .
108             ($stat->{action} && $stat->{comment} ? " " : "") . ($stat->{comment} ? '- ' . $stat->{comment} : ""),
109 39     39   2282 $stat->{elapsed},
110 39         111 $stat->{action} ? 1 : 0,
111             );
112             # Trim down any times >= 10 to avoid ugly Text::Simple line wrapping
113             my $elapsed = substr(sprintf("%f", $stat->{elapsed}), 0, 8) . "s";
114             if ($t) {
115 39 100 100     177 $t->row( ( q{ } x $r[0] ) . $r[1],
    100 100        
    100          
116             defined $r[2] ? $elapsed : '??');
117             }
118 39         637 else {
119 39 100       124 push @results, \@r;
120 28 50       176 }
121             });
122             return wantarray ? @results : $t->draw;
123             }
124 11         39  
125             my ($self, $uid) = @_;
126 16         1775  
127 16 100       1965 my $visitor = Tree::Simple::Visitor::FindByUID->new;
128             $visitor->searchForUID($uid);
129             $self->accept($visitor);
130             return $visitor->getResult;
131 5     5   14 }
132              
133 5         36 my $self = shift;
134 5         169 my $node = $_[ 0 ];
135 5         51  
136 5         582 my $stat = $node->getNodeValue;
137              
138             # do we need to fake $stat->{ t } ?
139             if( $stat->{ elapsed } ) {
140 1     1 1 36 # remove the "s" from elapsed time
141 1         2 $stat->{ elapsed } =~ s{s$}{};
142             }
143 1         5  
144             $self->tree->addChild( @_ );
145             }
146 1 50       6  
147             my $self = shift;
148 1         19 my $stat = $_[ 0 ];
149              
150             # do we need to fake $stat->{ t } ?
151 1         29 if( $stat->{ elapsed } ) {
152             # remove the "s" from elapsed time
153             $stat->{ elapsed } =~ s{s$}{};
154             }
155 1     1 1 10  
156 1         2 $self->tree->setNodeValue( @_ );
157             }
158              
159 1 50       5 my $self = shift;
160             $self->tree->getNodeValue( @_ )->{ t };
161 1         5 }
162              
163             __PACKAGE__->meta->make_immutable();
164 1         27  
165             1;
166              
167              
168 1     1 1 10 =for stopwords addChild getNodeValue mysub rollup setNodeValue
169 1         27  
170             =head1 NAME
171              
172             Catalyst::Stats - Catalyst Timing Statistics Class
173              
174             =head1 SYNOPSIS
175              
176             $stats = $c->stats;
177             $stats->enable(1);
178             $stats->profile($comment);
179             $stats->profile(begin => $block_name, comment =>$comment);
180             $stats->profile(end => $block_name);
181             $elapsed = $stats->elapsed;
182             $report = $stats->report;
183              
184             See L<Catalyst>.
185              
186             =head1 DESCRIPTION
187              
188             This module provides the default, simple timing stats collection functionality for Catalyst.
189             If you want something different set C<< MyApp->stats_class >> in your application module,
190             e.g.:
191              
192             __PACKAGE__->stats_class( "My::Stats" );
193              
194             If you write your own, your stats object is expected to provide the interface described here.
195              
196             Catalyst uses this class to report timings of component actions. You can add
197             profiling points into your own code to get deeper insight. Typical usage might
198             be like this:
199              
200             sub mysub {
201             my ($c, ...) = @_;
202             $c->stats->profile(begin => "mysub");
203             # code goes here
204             ...
205             $c->stats->profile("starting critical bit");
206             # code here too
207             ...
208             $c->stats->profile("completed first part of critical bit");
209             # more code
210             ...
211             $c->stats->profile("completed second part of critical bit");
212             # more code
213             ...
214             $c->stats->profile(end => "mysub");
215             }
216              
217             Supposing mysub was called from the action "process" inside a Catalyst
218             Controller called "service", then the reported timings for the above example
219             might look something like this:
220              
221             .----------------------------------------------------------------+-----------.
222             | Action | Time |
223             +----------------------------------------------------------------+-----------+
224             | /service/process | 1.327702s |
225             | mysub | 0.555555s |
226             | - starting critical bit | 0.111111s |
227             | - completed first part of critical bit | 0.333333s |
228             | - completed second part of critical bit | 0.111000s |
229             | /end | 0.000160s |
230             '----------------------------------------------------------------+-----------'
231              
232             which means mysub took 0.555555s overall, it took 0.111111s to reach the
233             critical bit, the first part of the critical bit took 0.333333s, and the second
234             part 0.111s.
235              
236              
237             =head1 METHODS
238              
239             =head2 new
240              
241             Constructor.
242              
243             $stats = Catalyst::Stats->new;
244              
245             =head2 enable
246              
247             $stats->enable(0);
248             $stats->enable(1);
249              
250             Enable or disable stats collection. By default, stats are enabled after object creation.
251              
252             =head2 profile
253              
254             $stats->profile($comment);
255             $stats->profile(begin => $block_name, comment =>$comment);
256             $stats->profile(end => $block_name);
257              
258             Marks a profiling point. These can appear in pairs, to time the block of code
259             between the begin/end pairs, or by themselves, in which case the time of
260             execution to the previous profiling point will be reported.
261              
262             The argument may be either a single comment string or a list of name-value
263             pairs. Thus the following are equivalent:
264              
265             $stats->profile($comment);
266             $stats->profile(comment => $comment);
267              
268             The following key names/values may be used:
269              
270             =over 4
271              
272             =item * begin => ACTION
273              
274             Marks the beginning of a block. The value is used in the description in the
275             timing report.
276              
277             =item * end => ACTION
278              
279             Marks the end of the block. The name given must match a previous 'begin'.
280             Correct nesting is recommended, although this module is tolerant of blocks that
281             are not correctly nested, and the reported timings should accurately reflect the
282             time taken to execute the block whether properly nested or not.
283              
284             =item * comment => COMMENT
285              
286             Comment string; use this to describe the profiling point. It is combined with
287             the block action (if any) in the timing report description field.
288              
289             =item * uid => UID
290              
291             Assign a predefined unique ID. This is useful if, for whatever reason, you wish
292             to relate a profiling point to a different parent than in the natural execution
293             sequence.
294              
295             =item * parent => UID
296              
297             Explicitly relate the profiling point back to the parent with the specified UID.
298             The profiling point will be ignored if the UID has not been previously defined.
299              
300             =back
301              
302             Returns the UID of the current point in the profile tree. The UID is
303             automatically assigned if not explicitly given.
304              
305             =head2 created
306              
307             ($seconds, $microseconds) = $stats->created;
308              
309             Returns the time the object was created, in C<gettimeofday> format, with
310             Unix epoch seconds followed by microseconds.
311              
312             =head2 elapsed
313              
314             $elapsed = $stats->elapsed
315              
316             Get the total elapsed time (in seconds) since the object was created.
317              
318             =head2 report
319              
320             print $stats->report ."\n";
321             $report = $stats->report;
322             @report = $stats->report;
323              
324             In scalar context, generates a textual report. In array context, returns the
325             array of results where each row comprises:
326              
327             [ depth, description, time, rollup ]
328              
329             The depth is the calling stack level of the profiling point.
330              
331             The description is a combination of the block name and comment.
332              
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.
336              
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.
339              
340             =head1 COMPATIBILITY METHODS
341              
342             Some components might expect the stats object to be a regular Tree::Simple object.
343             We've added some compatibility methods to handle this scenario:
344              
345             =head2 accept
346              
347             =head2 addChild
348              
349             =head2 setNodeValue
350              
351             =head2 getNodeValue
352              
353             =head2 traverse
354              
355             =head1 SEE ALSO
356              
357             L<Catalyst>
358              
359             =head1 AUTHORS
360              
361             Catalyst Contributors, see Catalyst.pm
362              
363             =head1 COPYRIGHT
364              
365             This library is free software. You can redistribute it and/or modify
366             it under the same terms as Perl itself.
367              
368             =cut
369              
370             __PACKAGE__->meta->make_immutable;
371              
372             1;