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 154     154   66504 use Time::HiRes qw/gettimeofday tv_interval/;
  154         388613  
  154         932  
4 154     154   912871 use Text::SimpleTable ();
  154         200379  
  154         2482  
5 154     154   30205 use Catalyst::Utils;
  154         2655  
  154         4777  
6 154     154   3007 use Tree::Simple qw/use_weak_refs/;
  154         374  
  154         4021  
7 154     154   2670 use Tree::Simple::Visitor::FindByUID;
  154         405  
  154         1518  
8 154     154   5798  
  154         2222  
  154         5164  
9             use namespace::clean -except => 'meta';
10 154     154   976  
  154         435  
  154         1135  
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 949 return unless $self->enable;
28              
29 76 100       1619 my %params;
30             if (@_ <= 1) {
31 75         107 $params{comment} = shift || "";
32 75 100       232 }
    50          
33 4   50     14 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         207 }
41 71   100     235  
42             my $parent;
43             my $prev;
44 75         113 my $t = [ gettimeofday ];
45             my $stack = $self->stack;
46 75         187  
47 75         1637 if ($params{end}) {
48             # parent is on stack; search for matching block and splice out
49 75 100       190 for (my $i = $#{$stack}; $i > 0; $i--) {
50             if ($stack->[$i]->getNodeValue->{action} eq $params{end}) {
51 33         64 my ($node) = splice(@{$stack}, $i, 1);
  33         97  
52 37 100       108 # Adjust elapsed on partner node
53 33         139 my $v = $node->getNodeValue;
  33         66  
54             $v->{elapsed} = tv_interval($v->{t}, $t);
55 33         69 return $node->getUID;
56 33         130 }
57 33         419 }
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       95 $prev = $parent = $self->_get_uid($params{parent});
63             }
64 5         14 if (!$parent) {
65             # Find previous node, which is either previous sibling or parent, for ref time.
66 42 100       172 $prev = $parent = $stack->[-1] or return undef;
67             my $n = $parent->getChildCount;
68 37 50       87 $prev = $parent->getChild($n - 1) if $n > 0;
69 37         113 }
70 37 100       215  
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     203  
79 42 100       2020 $parent->addChild($node);
80             push(@{$stack}, $node) if $params{begin};
81 42         222  
82 42 100       3463 return $node->getUID;
  34         63  
83             }
84 42         100  
85             return @{ shift->{tree}->getNodeValue->{t} };
86             }
87              
88 1     1 1 605 return tv_interval(shift->{tree}->getNodeValue->{t});
  1         4  
89             }
90              
91             my $self = shift;
92 16     16 1 2083  
93             my $t;
94             my @results;
95              
96 16     16 1 52 if (!wantarray) {
97             $t = Text::SimpleTable->new(
98 16         29 [ Catalyst::Utils::term_width() - 9 - 13, 'Action' ],
99             [ 9, 'Time' ],
100             );
101 16 100       40 }
102 15         47  
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   1886 $stat->{elapsed},
110 39         83 $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     131 $t->row( ( q{ } x $r[0] ) . $r[1],
    100 100        
    100          
116             defined $r[2] ? $elapsed : '??');
117             }
118 39         566 else {
119 39 100       77 push @results, \@r;
120 28 50       175 }
121             });
122             return wantarray ? @results : $t->draw;
123             }
124 11         24  
125             my ($self, $uid) = @_;
126 16         1302  
127 16 100       1537 my $visitor = Tree::Simple::Visitor::FindByUID->new;
128             $visitor->searchForUID($uid);
129             $self->accept($visitor);
130             return $visitor->getResult;
131 5     5   10 }
132              
133 5         26 my $self = shift;
134 5         121 my $node = $_[ 0 ];
135 5         39  
136 5         460 my $stat = $node->getNodeValue;
137              
138             # do we need to fake $stat->{ t } ?
139             if( $stat->{ elapsed } ) {
140 1     1 1 33 # remove the "s" from elapsed time
141 1         2 $stat->{ elapsed } =~ s{s$}{};
142             }
143 1         3  
144             $self->tree->addChild( @_ );
145             }
146 1 50       6  
147             my $self = shift;
148 1         26 my $stat = $_[ 0 ];
149              
150             # do we need to fake $stat->{ t } ?
151 1         25 if( $stat->{ elapsed } ) {
152             # remove the "s" from elapsed time
153             $stat->{ elapsed } =~ s{s$}{};
154             }
155 1     1 1 7  
156 1         2 $self->tree->setNodeValue( @_ );
157             }
158              
159 1 50       4 my $self = shift;
160             $self->tree->getNodeValue( @_ )->{ t };
161 1         4 }
162              
163             __PACKAGE__->meta->make_immutable();
164 1         22  
165             1;
166              
167              
168 1     1 1 8 =for stopwords addChild getNodeValue mysub rollup setNodeValue
169 1         21  
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;