Debian Codegraph @

bin/nytprofhtml

raw ◀ ▶
2 Debian patches touch this file
1 #!/usr/bin/perl
2 ##########################################################
3 ## This script is part of the Devel::NYTProf distribution
4 ##
5 ## Copyright, contact and other information can be found
6 ## at the bottom of this file, or by going to:
7 ## https://metacpan.org/pod/Devel::NYTProf
8 ##
9 ###########################################################
10
11 =head1 NAME
12
13 nytprofhtml - Generate reports from Devel::NYTProf data
14
15 =head1 SYNOPSIS
16
17 Typical usage:
18
19 $ perl -d:NYTProf some_perl_app.pl
20 $ nytprofhtml --open
21
22 Options synopsis:
23
24 $ nytprofhtml [-h] [-d] [-m] [-o <output directory>] [-f <input file>] [--open]
25
26 =encoding ISO8859-1
27
28 =cut
29
30 use warnings;
31 use strict;
32
33 use Carp;
34 use Config qw(%Config);
35 use Getopt::Long;
36 use List::Util qw(sum max);
37 use File::Copy;
38 use File::Spec;
39 use File::Which qw(which);
40 use File::Path qw(rmtree);
41
42 # Handle --profself before loading Devel::NYTProf::Core
43 # (because it parses NYTPROF for options)
44 BEGIN {
45 if (grep { $_ eq '--profself' } @ARGV) {
46 # profile nytprofhtml itself
47 our $profself = "nytprof-nytprofhtml.out";
48 $ENV{NYTPROF} .= ":file=$profself:trace=1";
49 require Devel::NYTProf;
50 END { warn "Profile of $0 written to $profself\n" if our $profself; }
51 }
52 }
53
54 use Devel::NYTProf::Reader;
55 use Devel::NYTProf::Core;
56 use Devel::NYTProf::Util qw(
57 fmt_float fmt_time fmt_incl_excl_time
58 calculate_median_absolute_deviation
59 get_abs_paths_alternation_regex
60 html_safe_filename
61 );
62 use Devel::NYTProf::Constants qw(NYTP_SCi_CALLING_SUB);
63
64 our $VERSION = '6.15';
65
66 if ($VERSION != $Devel::NYTProf::Core::VERSION) {
67 die "$0 version '$VERSION' doesn't match version '$Devel::NYTProf::Core::VERSION' of $INC{'Devel/NYTProf/Core.pm'}\n";
68 }
69
70 my $has_json = eval { require JSON::MaybeXS; JSON::MaybeXS->import(); 1 }
71 or warn "Can't load JSON::MaybeXS module - HTML visualizations skipped ($@)\n";
72
73 my $script_ext = ($^O eq "MSWin32") ? "" : ".pl";
74
75 my $nytprofcalls = File::Spec->catfile($Config{'bin'}, 'nytprofcalls');
76 $nytprofcalls = which 'nytprofcalls' if not -e $nytprofcalls;
77
78 die "Unable to find nytprofcalls in $Config{bin} or on the PATH"
79 unless $nytprofcalls;
80
81 my $flamegraph = File::Spec->catfile($Config{'bin'}, 'flamegraph') . $script_ext;
82 $flamegraph = which "flamegraph$script_ext" if not -e $flamegraph;
•83 $flamegraph = '/usr/share/perl5/Devel/NYTProf/flamegraph.pl';
84
85 die "Unable to find flamegraph$script_ext in $Config{bin} or on the PATH"
86 unless $flamegraph;
87
88 my @treemap_colors = (0,2,4,6,8,10,1,3,5,7,9);
89
90 # These control the limits for what the script will consider ok to severe times
91 # specified in standard deviations from the mean time
92 use constant SEVERITY_SEVERE => 2.0; # above this deviation, a bottleneck
93 use constant SEVERITY_BAD => 1.0;
94 use constant SEVERITY_GOOD => 0.5; # within this deviation, okay
95
96 use constant NUMERIC_PRECISION => 5;
97
98 my @on_ready_js;
99
100 GetOptions(
101 'file|f=s' => \(my $opt_file = 'nytprof.out'),
102 'lib|l=s' => \my $opt_lib,
103 'out|o=s' => \(my $opt_out = 'nytprof'),
104 'delete|d!' => \my $opt_delete,
105 'open!' => \my $opt_open,
106 'help|h' => sub { exit usage() },
107 'minimal|m!'=> \my $opt_minimal,
108 'flame!' => \(my $opt_flame = 1),
109 'mergeevals!'=> \(my $opt_mergeevals = 1),
110 'flamewidth=i' => \(my $opt_flame_width = 1200),
111 'profself!' => sub { }, # handled in BEGIN above
112 'debug!' => \my $opt_debug,
113 ) or do { exit usage(); };
114
115
116 DB::set_option('blocks', 0) if $opt_minimal;
117
118 sub usage {
119 print <<END;
120 usage: [perl] nytprofhtml [opts]
121 --file <file>, -f <file> Read profile data from the specified file [default: nytprof.out]
122 --out <dir>, -o <dir> Write report files to this directory [default: nytprof]
123 --delete, -d Delete any old report files in <dir> first
124 --open Open the generated report in a web browser
125 --lib <lib>, -l <lib> Add <lib> to the beginning of \@INC
126 --no-flame Disable flame graph (and call stacks processing)
127 --flamewidth <width> Width of the flame graph [default: 1200]
128 --minimal, -m Don't generate graphviz .dot files or block/sub-level reports
129 --no-mergeevals Disable merging of string evals
130 --help, -h Print this message
131
132 This script is part of the Devel::NYTProf distribution.
133 See http://metacpan.org/release/Devel-NYTProf/ for details and copyright.
134 END
135 return 0;
136 }
137
138
139 # handle output location
140 if (!-e $opt_out) {
141 # will be created
142 }
143 elsif (!-d $opt_out) {
144 die "$0: Specified output directory '$opt_out' already exists as a file!\n";
145 }
146 elsif (!-w $opt_out) {
147 die "$0: Unable to write to output directory '$opt_out'\n";
148 }
149 else {
150 if (defined($opt_delete)) {
151 print "Deleting existing $opt_out directory\n";
152 rmtree($opt_out);
153 }
154 }
155
156 # handle custom lib path
157 if (defined($opt_lib)) {
158 warn "$0: Specified lib directory '$opt_lib' does not exist.\n"
159 unless -d $opt_lib;
160 require lib;
161 lib->import($opt_lib);
162 }
163
164 $SIG{USR2} = \&Carp::cluck
165 if exists $SIG{USR2}; # some platforms don't have SIGUSR2 (Windows)
166
167 my $reporter = new Devel::NYTProf::Reader($opt_file, {
168 quiet => 0,
169 skip_collapse_evals => !$opt_mergeevals,
170 });
171
172 # place to store this
173 $reporter->output_dir($opt_out);
174
175 # set formatting for html
176 $reporter->set_param(
177 'header',
178 sub {
179 my ($profile, $fi, $output_filestr, $level) = @_;
180
181 my $profile_level_buttons = ($fi->is_eval)
182 ? '' : get_level_buttons($profile->get_profile_levels, $output_filestr, $level);
183
184 my $subhead = qq{&emsp;&emsp;$profile_level_buttons<br />
185 For ${ \($profile->{attribute}{application}) }
186 };
187
188 my $html_header = get_html_header("Profile of ".$fi->filename_without_inc);
189 my $page_header = get_page_header(
190 profile => $profile,
191 title => "NYTProf Performance Profile",
192 subtitle => $subhead,
193 );
194 my $filename_escaped = _escape_html($fi->filename);
195 my @intro_rows = (
196 [ "Filename", $fi->is_file
197 ? sprintf(q{<a href="file://%s">%s</a>}, $fi->filename, $filename_escaped)
198 : $filename_escaped ],
199 [ "Statements", sprintf "Executed %d statements in %s",
200 $fi->sum_of_stmts_count, fmt_time($fi->sum_of_stmts_time) ],
201 );
202 if ($fi->is_eval) {
203 push @intro_rows, [
204 "Eval Invoked At", sprintf q{<a %s>%s line %d</a>},
205 $reporter->href_for_file($fi->eval_fi, $fi->eval_line),
206 _escape_html($fi->eval_fi->filename), $fi->eval_line
207 ];
208
209 my @sibling_html;
210 for my $e_fi ($fi->sibling_evals) {
211 if ($e_fi == $fi) {
212 push @sibling_html, 1+@sibling_html;
213 }
214 else {
215 push @sibling_html, sprintf qq{<a %s>%d</a>},
216 $reporter->href_for_file($e_fi),
217 1+@sibling_html;
218 }
219 }
220 push @intro_rows, [ "Sibling evals",
221 join ", ", @sibling_html
222 ] if @sibling_html >= 2;
223 }
224
225 my $intro_table = join "\n", map {
226 sprintf q{<tr><td class="h">%s</td><td align="left">%s</td></tr>}, @$_
227 } @intro_rows;
228
229 return join "\n", $html_header, $page_header,
230 q{<div class="body_content"><br />},
231 qq{<table class="file_summary">$intro_table</table>},
232 }
233 );
234
235 $reporter->set_param(
236 'taintmsg',
237 qq{<br /><div class="warn_title">WARNING!</div>\n
238 <div class="warn">The source file used to generate this report was modified
239 after the profiler data was generated.
240 The data might be out of sync with the modified source code so you should regenerate it.
241 Meanwhile, the data on this page might not make much sense!</div>\n}
242 );
243
244 $reporter->set_param(
245 'sawampersand',
246 sub {
247 my ($profile, $fi) = @_;
248 my $line = $profile->{attribute}{sawampersand_line};
249 return qq{<br /><div class="warn_title">NOTE!</div>\n
250 <div class="warn"><p>While profiling this file Perl noted the use of one or more special
251 variables that impact the performance of <i>all</i> regular expressions in the program.</p>
252
253 <p>Use of the "<tt>\$`</tt>", "<tt>\$&</tt>", and "<tt>\$'</tt>" variables should be replaced with faster alternatives.<br />
254 See the WARNING at the end of the <a href="http://perldoc.perl.org/perlre.html#Capture-buffers">
255 Capture Buffers section of the perlre documentation</a>.</p>
256
257 <p>The use is detected by perl at compile time but by NYTProf during execution.
258 NYTProf first noted it when executing <a href="#$line">line $line</a>.
259 That was probably the first statement executed by the program after perl
260 compiled the code containing the variables.
261 If the variables can't be found by studying the source code, try using the
262 <a href="http://metacpan.org/pod/Devel::FindAmpersand">Devel::FindAmpersand</a>
263 or <a href="http://metacpan.org/pod/B::Lint">B::Lint</a>
264 modules.</p>
265
266 </div>\n}
267 }
268 ) if $] < 5.017008;
269
270 $reporter->set_param(
271 'merged_fids',
272 sub {
273 my ($profile, $fi) = @_;
274
275 my $merged_fids = $fi->meta->{merged_fids};
276 my $evals_shown = 1 + scalar @$merged_fids;
277
278 my @siblings = $fi->sibling_evals;
279 my $merged_siblings = sum(map { scalar @{$_->meta->{merged_fids}||[]} } @siblings);
280 my $evals_total = @siblings + $merged_siblings;
281
282 my @msg;
283 push @msg, sprintf qq{
284 The data used to generate this report page was merged from %s<br />
285 of the string eval on line %d of %s.
286 }, ($evals_shown == $evals_total)
287 ? sprintf("all %d executions", $evals_shown)
288 : sprintf("%d of the %d executions", $evals_shown, $evals_total),
289 $fi->eval_line, $fi->eval_fi->filename;
290
291 push @msg, qq{
292 The source code shown below is the text of just one of the calls to the eval.<br />\n
293 This report page might not make much sense because the argument source code of those eval calls varied.<br />\n
294 } if $fi->meta->{merged_fids_src_varied};
295
296 return sprintf qq{<br /><div class="warn_title">NOTE!</div>\n
297 <div class="warn">%s</div>
298 }, join "<br />", @msg;
299 },
300 );
301
302
303 sub calc_mad_from_objects {
304 my ($ary, $meth, $ignore_zeros) = @_;
305 return calculate_median_absolute_deviation([map { scalar $_->$meth } @$ary], $ignore_zeros);
306 }
307
308 sub subroutine_table {
309 my ($profile, $fi, $max_subs, $sortby) = @_;
310 $sortby ||= 'excl_time';
311
312 my $subs_in_file = ($fi)
313 ? $profile->subs_defined_in_file($fi, 0)
314 : $profile->subname_subinfo_map;
315 return "" unless $subs_in_file && %$subs_in_file;
316
317 my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);
318 my $filestr = ($fi) ? $fi->filename : undef;
319
320 # XXX slow - use Schwartzian transform or via XS or Sort::Key
321 my @subs =
322 sort { $b->$sortby <=> $a->$sortby or $a->subname cmp $b->subname }
323 values %$subs_in_file;
324
325 # in the overall summary, don't show subs that were never called
326 @subs = grep { $_->calls > 0 } @subs if !$fi;
327
328 my $dev_incl_time = calc_mad_from_objects(\@subs, 'incl_time', 1);
329 my $dev_excl_time = calc_mad_from_objects(\@subs, 'excl_time', 1);
330 my $dev_calls = calc_mad_from_objects(\@subs, 'calls', 1);
331 my $dev_call_count = calc_mad_from_objects(\@subs, 'caller_count', 1);
332 my $dev_call_fids = calc_mad_from_objects(\@subs, 'caller_fids', 1);
333
334 my @subs_to_show = ($max_subs) ? splice @subs, 0, $max_subs : @subs;
335 my $qualifier = (@subs > @subs_to_show) ? "Top $max_subs " : "";
336 my $max_pkg_name_len = max(map { length($_->package) } @subs_to_show);
337
338 my $sub_links;
339
340 my $sortby_desc = ($sortby eq 'excl_time') ? "exclusive time" : "inclusive time";
341 $sub_links .= qq{
342 <table id="subs_table" border="1" cellpadding="0" class="tablesorter floatHeaders">
343 <caption>${qualifier}Subroutines</caption>
344 <thead>
345 <tr>
346 <th>Calls</th>
347 <th><span title="Number of Places sub is called from">P</span></th>
348 <th><span title="Number of Files sub is called from">F</span></th>
349 <th>Exclusive<br />Time</th>
350 <th>Inclusive<br />Time</th>
351 <th>Subroutine</th>
352 </tr>
353 </thead>
354 };
355
356 my $profiler_active = $profile->{attribute}{profiler_active};
357
358 my @rows;
359 $sub_links .= "<tbody>\n";
360 for my $sub (@subs_to_show) {
361
362 $sub_links .= "<tr>";
363
364 $sub_links .= determine_severity($sub->calls || 0, $dev_calls);
365 $sub_links .= determine_severity($sub->caller_count || 0, $dev_call_count);
366 $sub_links .= determine_severity($sub->caller_fids || 0, $dev_call_fids);
367 $sub_links .= determine_severity($sub->excl_time || 0, $dev_excl_time, 1,
368 sprintf("%.1f%%", $sub->excl_time/$profiler_active*100)
369 );
370 $sub_links .= determine_severity($sub->incl_time || 0, $dev_incl_time, 1,
371 sprintf("%.1f%%", $sub->incl_time/$profiler_active*100)
372 );
373
374 my @hints;
375
376 # package and subname
377 my $subname = $sub->subname;
378 if (my $merged_sub_names = $sub->meta->{merged_sub_names}) {
379 push @hints, sprintf "merge of %d subs", 1+scalar @$merged_sub_names;
380 }
381 my ($pkg, $subr) = ($subname =~ /^(.*::)(.*?)$/) ? ($1, $2) : ('', $subname);
382
383 # remove OWN filename from eg __ANON__[(eval 3)[/long/path/name.pm:99]:53]
384 # becomes __ANON__[(eval 3)[:99]:53]
385 # XXX doesn't work right if $filestr isn't full filename
386 $subr =~ s/\Q$filestr\E:(\d+)/:$1/g if $filestr;
387 # remove @INC prefix from other paths
388 $subr =~ s/$inc_path_regex//; # for __ANON__[/very/long/path...]
389
390 $sub_links .= qq{<td class="sub_name">};
391 # hidden span is for tablesorter to sort on
392 $sub_links .= sprintf(qq{<span style="display: none;">%s::%s</span>}, $pkg, $subr);
393
394 if ($sub->is_xsub) {
395 my $is_opcode = ($pkg eq 'CORE' or $subr =~ /^CORE:/);
396 unshift @hints, ($is_opcode) ? 'opcode' : 'xsub';
397 }
398 if (my $recdepth = $sub->recur_max_depth) {
399 unshift @hints, sprintf "recurses: max depth %d, inclusive time %s",
400 $recdepth, fmt_time($sub->recur_incl_time);
401 }
402
403 $sub_links .= sprintf qq{%*s<a %s>%s</a>%s</td>},
404 $max_pkg_name_len+2, $pkg,
405 $reporter->href_for_sub($subname),
406 $subr,
407 (@hints) ? "&nbsp;(".join("; ",@hints).")" : "";
408
409 $sub_links .= "</tr>\n";
410 }
411 $sub_links .= q{</tbody>};
412 $sub_links .= q{</table>};
413
414 # make table sortable if it contains all the subs
415 push @on_ready_js, q<
416 $("#subs_table").tablesorter({
417 sortList: [[3,1]],
418 headers: {
419 3: { sorter: 'fmt_time' },
420 4: { sorter: 'fmt_time' }
421 }
422 });
423 $(".floatHeaders").each( function(){ $(this).floatThead(); } );
424
425 show_fragment_target();
426 $(window).on('hashchange', function(e){
427 show_fragment_target();
428 });
429
430 > if @subs_to_show == @subs;
431
432 return $sub_links;
433 }
434
435
436 $reporter->set_param(
437 'datastart',
438 sub {
439 my ($profile, $fi) = @_;
440 my $filestr = $fi->filename;
441
442 my $sub_table = subroutine_table($profile, $fi, undef, undef);
443
444 if ($sub_table and not $opt_minimal) {
445 my $dot_file = html_safe_filename($filestr) . ".dot";
446
447 $sub_table .= qq{
448 Call graph for these subroutines as a
449 <a href="http://en.wikipedia.org/wiki/Graphviz">Graphviz</a>
450 <a href="$dot_file">dot language file</a>.
451 };
452
453 our %dot_file_generated;
454 if ($dot_file_generated{$dot_file}++) { # just once for line/block/sub
455 my $subs_in_file = $profile->subs_defined_in_file($filestr, 0);
456 # include subs defined in this file
457 # and/or called from subs defined in this file
458 #warn "$dot_file: @{[ keys %$subs_in_file ]}\n";
459 my $sub_filter = sub {
460 my ($si, $calledby) = @_;
461 return 1 if not defined $calledby;
462 my $subname = $si->subname;
463 my $include = ($subs_in_file->{$subname}
464 || $subs_in_file->{$calledby});
465 #warn "Call graph $subname<-$calledby: ".($include ? "SHOW" : "skip")."\n";
466 return $include;
467 };
468 output_subs_callgraph_dot_file($reporter, $dot_file, $sub_filter, 0);
469 }
470 }
471
472 return qq{
473 $sub_table
474 <table border="1" cellpadding="0" class="floatHeaders">
475 <thead>
476 <tr><th>Line</th>
477 <th><span title="Number of statements executed">State<br />ments</span></th>
478 <th><span title="Time spent executing statements on the line,
479 excluding time spent executing statements in any called subroutines">Time<br />on line</span></th>
480 <th><span title="Number of subroutines calls">Calls</span></th>
481 <th><span title="Time spent in subroutines called (inclusive)">Time<br />in subs</span></th>
482 <th class="left_indent_header">Code</th>
483 </tr>\n
484 </thead>
485 <tbody>
486 };
487 }
488 );
489
490 $reporter->set_param( footer => sub {
491 my ($profile, $fi) = @_;
492 my $footer = get_footer($profile);
493 return "</tbody></table></div>$footer</body></html>";
494 } );
495
496 $reporter->set_param(mk_report_source_line => \&mk_report_source_line);
497 $reporter->set_param(mk_report_xsub_line => \&mk_report_xsub_line );
498 $reporter->set_param(mk_report_separator_line => \&mk_report_separator_line );
499
500 sub mk_report_source_line {
501 my ($linenum, $line, $stats_for_line, $stats_for_file, $profile, $fi) = @_;
502
503 my $l = sprintf(qq{<td class="h"><a name="%s"></a>%s</td>}, $linenum, $linenum);
504 my $s = report_src_line(undef, $linenum, $line, $profile, $fi, $stats_for_line);
505
506 return "<tr>$l<td></td><td></td><td></td><td></td>$s</tr>\n"
507 if not %$stats_for_line;
508
509 return join "",
510 "<tr>$l",
511 determine_severity($stats_for_line->{'calls'}, $stats_for_file->{'calls'}),
512 determine_severity($stats_for_line->{'time'}, $stats_for_file->{'time'}, 1,
513 \sprintf("Avg %s", fmt_time($stats_for_line->{'time/call'})||'--' )),
514 determine_severity($stats_for_line->{'subcall_count'}, $stats_for_file->{subcall_count}, 0),
515 determine_severity($stats_for_line->{'subcall_time'}, $stats_for_file->{subcall_time}, 1),
516 $s, "</tr>\n";
517 }
518
519 sub mk_report_xsub_line {
520 my ($subname, $line, $stats_for_line, $stats_for_file, $profile, $fi) = @_;
521 (my $anchor = $subname) =~ s/\W/_/g;
522 return join "",
523 sprintf(qq{<tr><td class="h"><a name="%s"></a>%s</td>}, $anchor, ''),
524 "<td></td><td></td><td></td><td></td>",
525 report_src_line(undef, undef, $line, $profile, $fi, $stats_for_line),
526 "</tr>\n";
527 }
528
529 sub mk_report_separator_line {
530 my ($profile, $fi) = @_;
531 return join "",
532 sprintf(qq{<tr><td class="s"><a name="%s"></a>%s</td>}, '', '&nbsp;'),
533 "<td></td><td></td><td></td><td></td>",
534 '<td class="s"></td>',
535 "</tr>\n";
536 }
537
538
539 sub _escape_html {
540 local $_ = shift;
541 s/\t/ /g; # XXX incorrect for most non-leading tabs
542 s/&/&amp;/g;
543 s/</&lt;/g;
544 s/>/&gt;/g;
545 s{\n}{<br />}g; # for xsub pseudo-sub declarations
546 s{"}{&quot;}g; # for attributes like title="..."
547 return $_;
548 }
549
550
551 sub report_src_line {
552 my ($value, undef, $linesrc, $profile, $fi, $stats_for_line) = @_;
553
554 $linesrc = _escape_html($linesrc);
555
556 our $inc_path_regex ||= get_abs_paths_alternation_regex([$profile->inc]);
557
558 my @prologue;
559
560 # for each of the subs defined on this line, who called them
561 my $subdef_info = $stats_for_line->{subdef_info} || [];
562 for my $sub_info (@$subdef_info) {
563 my $callers = $sub_info->caller_fid_line_places;
564 next unless $callers && %$callers;
565 my $subname = $sub_info->subname;
566
567 my @callers;
568 while (my ($fid, $fid_line_info) = each %$callers) {
569 for my $line (keys %$fid_line_info) {
570 my $sc = $fid_line_info->{$line};
571 warn "$linesrc $subname caller info missing" if !@$sc;
572 next if !@$sc;
573 push @callers, [ $fid, $line, @$sc ];
574 }
575 }
576 my $total_calls = sum(my @caller_calls = map { $_->[2] } @callers);
577
578 push @prologue, sprintf "# spent %s within %s which was called%s:",
579 fmt_incl_excl_time($sub_info->incl_time, $sub_info->excl_time),
580 $subname,
581 ($total_calls <= 1) ? ""
582 : sprintf(" %d times, avg %s/call",
583 $total_calls, fmt_time($sub_info->incl_time / $total_calls));
584 push @prologue, sprintf "# (data for this subroutine includes %d others that were merged with it)",
585 scalar @{$sub_info->meta->{merged_sub_names}}
586 if $sub_info->meta->{merged_sub_names};
587 my $max_calls = max(@caller_calls);
588
589 # order by most frequent caller first, then by time
590 @callers = sort { $b->[2] <=> $a->[2] || $b->[3] <=> $a->[3] } @callers;
591
592 for my $caller (@callers) {
593 my ($fid, $line, $count, $incl_time, $excl_time, undef, undef,
594 undef, undef, $calling_subs) = @$caller;
595
596 my @subnames = sort keys %{$calling_subs || {}};
597 my $subname = (@subnames) ? " by " . join(" or ", @subnames) : "";
598
599 my $caller_fi = $profile->fileinfo_of($fid);
600 if (!$caller_fi) { # should never happen
601 warn sprintf "Caller of %s, from fid %d line %d has no fileinfo (%s)",
602 $sub_info, $fid, $line, $subname;
603 die 2;
604 next;
605 }
606
607 my $avg_time = "";
608 $avg_time = sprintf ", avg %s/call", fmt_time($incl_time / $count)
609 if $count > 1;
610 my $times = sprintf " (%s+%s)", fmt_time($excl_time),
611 fmt_time($incl_time - $excl_time);
612
613 my $filename = $caller_fi->filename($fid);
614 my $line_desc = "line $line of $filename";
615 $line_desc =~ s/ of \Q$filename\E$//g if $filename eq $fi->filename;
616 # remove @INC prefix from paths
617 $line_desc =~ s/$inc_path_regex//g;
618
619 my $href = $reporter->href_for_file($caller_fi, $line);
620 push @prologue,
621 sprintf q{# %*s times%s%s at <a %s>%s</a>%s},
622 length($max_calls), $count, $times, $subname, $href,
623 $line_desc, $avg_time;
624 $prologue[-1] =~ s/^(# +)1 times/$1 once/; # better English
625 }
626 }
627 my $prologue = '';
628 $prologue = sprintf qq{<div class="calls"><div class="calls_in">%s</div></div>}, join("\n", @prologue)
629 if @prologue;
630
631 my $epilogue = '';
632 my $ws;
633
634 # give details of each of the subs called by this line
635 my $subcall_info = $stats_for_line->{subcall_info};
636 if ($subcall_info && %$subcall_info) {
637
638 my @calls_to = sort {
639 $subcall_info->{$b}[1] <=> $subcall_info->{$a}[1] or # incl_time
640 $a cmp $b
641 } keys %$subcall_info;
642 my $max_calls_to = max(map { $_->[0] } values %$subcall_info);
643 $ws ||= ($linesrc =~ m/^((?:&nbsp;|\s)+)/) ? $1 : '';
644
645 my $subs_called_html = join "\n", map {
646 my $subname = $_;
647 my ($count, $incl_time, $reci_time, $rec_depth) = (@{$subcall_info->{$subname}})[0,1,5,6];
648 my $html = sprintf qq{%s# spent %s making %*d call%s to }, $ws,
649 fmt_time($incl_time+$reci_time, 5), length($max_calls_to),
650 $count, $count == 1 ? "" : "s";
651 (my $subname_trimmed = $subname) =~ s/$inc_path_regex//g;
652 $html .= sprintf qq{<a %s>%s</a>}, $reporter->href_for_sub($subname), $subname_trimmed;
653 $html .= sprintf qq{, avg %s/call}, fmt_time(($incl_time+$reci_time) / $count),
654 if $count > 1;
655 if ($rec_depth) {
656 $html .= sprintf qq{, recursion: max depth %d, sum of overlapping time %s},
657 $rec_depth, fmt_time($reci_time);
658 }
659 $html;
660 } @calls_to;
661 $epilogue .= sprintf qq{<div class="calls"><div class="calls_out">%s</div></div>}, $subs_called_html;
662 }
663
664 # give details of each of the string evals executed on this line
665 my $evals_called = $stats_for_line->{evalcall_info};
666 if ($evals_called && %$evals_called) {
667 $ws ||= ($linesrc =~ m/^((?:&nbsp;|\s)+)/) ? $1 : '';
668
669 my @eval_fis = sort {
670 $b->sum_of_stmts_time(1) <=> $a->sum_of_stmts_time(1) or
671 $a->filename cmp $b->filename
672 } values %$evals_called;
673
674 my $evals_called_html = join "\n", map {
675 my $eval_fi = $_;
676 my $sum_of_stmts_time = $eval_fi->sum_of_stmts_time;
677 my ($what, $extra) = ("string eval", "");
678
679 my $merged_fids = $eval_fi->meta->{merged_fids};
680 if ($merged_fids) {
681 $what = sprintf "%d string evals (merged)", 1+@$merged_fids;
682 }
683
684 my @nested_evals = $eval_fi->has_evals(1);
685 my $nest_eval_time = 0;
686 if (@nested_evals) {
687 $nest_eval_time = sum map { $_->sum_of_stmts_time } @nested_evals;
688 $extra .= sprintf ", %s here plus %s in %d nested evals",
689 fmt_time($sum_of_stmts_time), fmt_time($nest_eval_time),
690 scalar @nested_evals
691 if $nest_eval_time;
692 }
693
694 if (my @subs_defined = $eval_fi->subs_defined(1)) {
695 my $sub_count = @subs_defined;
696 my $call_count = sum map { $_->calls } @subs_defined;
697 my $excl_time = sum map { $_->excl_time } @subs_defined;
698 $extra .= sprintf "<br />%s# includes %s spent executing %d call%s to %d sub%s defined therein.",
699 $ws, fmt_time($excl_time, 2),
700 $call_count, ($call_count != 1) ? 's' : '',
701 $sub_count, ($sub_count != 1) ? 's' : ''
702 if $call_count;
703 }
704
705 my $link = sprintf(q{<a %s>%s</a>}, $reporter->href_for_file($eval_fi), $what);
706 my $html = sprintf qq{%s# spent %s executing statements in %s%s},
707 $ws, fmt_time($sum_of_stmts_time+$nest_eval_time, 5),
708 $link, $extra;
709
710 $html;
711 } @eval_fis;
712
713 $epilogue .= sprintf qq{<div class="calls"><div class="calls_out">%s</div></div>}, $evals_called_html;
714 }
715
716 return qq{<td class="s">$prologue$linesrc$epilogue</td>};
717 }
718
719
720 # set output options
721 $reporter->set_param('suffix', '.html');
722
723 # output a css file too (optional, but good for pretty pages)
724 $reporter->_output_additional('style.css', get_css());
725
726 # generate the files
727 $reporter->report();
728
729 output_subs_index_page($reporter, "index-subs-excl.html", 'excl_time');
730 output_index_page($reporter, "index.html");
731
732 output_js_files($reporter);
733
734 open_browser_on("$opt_out/index.html") if $opt_open;
735
736 exit 0;
737
738 #
739 # SUBROUTINES
740 #
741
742 # output an html indexing page or subroutines
743 sub output_subs_index_page {
744 my ($r, $filename, $sortby) = @_;
745 my $profile = $reporter->{profile};
746
747 open my $fh, '>', "$opt_out/$filename"
748 or croak "Unable to open file $opt_out/$filename: $!";
749
750 print $fh get_html_header("Subroutine Index - NYTProf");
751 print $fh get_page_header(profile => $profile, title => "Performance Profile Subroutine Index");
752 print $fh qq{<div class="body_content"><br />};
753
754 # Show top subs across all files
755 print $fh subroutine_table($profile, undef, 0, $sortby);
756
757 my $footer = get_footer($profile);
758 print $fh "</div>$footer</body></html>";
759 close $fh;
760 }
761
762
763 # output an html indexing page with some information to help navigate potential
764 # large numbers of profiled files. Optional, recommended
765 sub output_index_page {
766 my ($r, $filename) = @_;
767 my $profile = $reporter->{profile};
768
769 ###
770 open my $fh, '>', "$opt_out/$filename"
771 or croak "Unable to open file $opt_out/$filename: $!";
772
773 my $application = $profile->{attribute}{application};
774 (my $app = $application) =~ s:.*/::; # basename
775 $app =~ s/ .*//;
776
777 print $fh get_html_header("NYTProf $app");
778 print $fh get_page_header(profile => $profile, title => "Performance Profile Index", skip_link_to_index=>1);
779 print $fh qq{
780 <div class="body_content"><br />
781 };
782
783 # overall description
784 my @all_fileinfos = $profile->all_fileinfos;
785 my $eval_fileinfos = $profile->eval_fileinfos;
786 my $summary = sprintf "Profile of %s for %s (of %s),", $application,
787 fmt_time($profile->{attribute}{profiler_active}),
788 fmt_time($profile->{attribute}{profiler_duration});
789 $summary .= " executing";
790 $summary .= sprintf " %d statements and",
791 $profile->{attribute}{total_stmts_measured}
792 -$profile->{attribute}{total_stmts_discounted}
793 if $profile->{option}{stmts};
794 $summary .= sprintf " %d subroutine calls",
795 $profile->{attribute}{total_sub_calls};
796 $summary .= sprintf " in %d source files",
797 @all_fileinfos - $eval_fileinfos;
798 $summary .= sprintf " and %d string evals",
799 $eval_fileinfos if $eval_fileinfos;
800 printf $fh qq{<div class="index_summary">%s.</div>}, _escape_html($summary);
801
802 # generate name-sorted select options for files, if there are many
803 if ($profile->noneval_fileinfos > 30) {
804 print $fh qq{<div class="jump_to_file"><form name="jump">};
805 print $fh qq{<select name="file" onChange="location.href=document.jump.file.value;">\n};
806 printf $fh qq{<option disabled="disabled">%s</option>\n}, "Jump to file...";
807 foreach my $fi (sort { $a->filename cmp $b->filename } $profile->noneval_fileinfos) {
808 printf $fh qq{<option value="#f%s">%s</option>\n},
809 $fi->fid, _escape_html($fi->filename);
810 }
811 print $fh "</select></form></div>\n";
812 }
813
814 my $call_stacks_file = "all_stacks_by_time.calls";
815 my $call_stacks_svg = "all_stacks_by_time.svg";
816 if ($profile->{option}{calls} && $opt_flame) {
817 my $mk_flamegraph = sub {
818
819 my $total_sub_calls = $profile->{attribute}{total_sub_calls};
820 my $is_big = ($total_sub_calls <= 1_000_000);
821 warn sprintf "Extracting subroutine call data%s ...\n",
822 ($is_big) ? "" : " (There were $total_sub_calls of them, so this may take some time, or cancel and use --no-flame to skip this step.)";
823 system("\"$nytprofcalls\" $opt_file > $opt_out/$call_stacks_file") == 0
824 or die "Generating $opt_out/$call_stacks_file failed\n";
825
826 my %subname_subinfo_map = %{ $profile->subname_subinfo_map };
827 warn "Extracting subroutine links\n";
828 my $subattr = "$opt_out/flamegraph_subattr.txt";
829 open my $subattrfh, ">", $subattr
830 or die "Error creating $subattr: $!\n";
831 while ( my ($subname, $si) = each %subname_subinfo_map ) {
832 next unless $si->incl_time;
833 print $subattrfh join("\t", $subname,
834 q{href=}.$reporter->url_for_sub($subname),
835 )."\n";
836 }
837 close $subattrfh or die "Error writing $subattr: $!\n";
838
839 warn "Generating subroutine stack flame graph ...\n";
840 # factor to scale the values to microseconds
841 my $factor = 1_000_000 / $profile->{attribute}{ticks_per_sec};
842 # total (width) for flamegraph is profiler_active in ticks
843 my $run_us = $profile->{attribute}{profiler_active} * $profile->{attribute}{ticks_per_sec};
844 system("\"$flamegraph\" --nametype=sub --countname=microseconds --factor=$factor --width=$opt_flame_width --nameattr=$subattr --hash --total=$run_us $opt_out/$call_stacks_file > $opt_out/$call_stacks_svg") == 0
845 or die "Generating $opt_out/$call_stacks_svg failed\n";
846
847 print $fh qq{<div class="flamegraph">\n};
848 print $fh qq{<object data="$call_stacks_svg" width="$opt_flame_width" type="image/svg+xml" >SVG not supported</object>\n};
849 print $fh qq{<p>The <a href="https://www.brendangregg.com/flamegraphs.html">Flame Graph</a> above is a visualization of the time spent in <em>distinct call stacks</em>. The colors and x-axis position are not meaningful.</p>\n};
850 print $fh qq{</div>\n};
851 1;
852 };
853 eval { $mk_flamegraph->() }
854 or warn $@;
855 }
856
857 # Show top subs across all files
858 my $max_subs = 15; # keep it less than a page so users can see the file table
859 my $all_subs = keys %{$profile->{sub_subinfo}};
860 print $fh subroutine_table($profile, undef, $max_subs, undef);
861 if ($all_subs > $max_subs) {
862 print $fh sprintf qq{<div class="table_footer">
863 See <a href="%s">all %d subroutines</a>
864 </div>
865 }, "index-subs-excl.html", $all_subs;
866 }
867
868 if ($has_json) {
869 output_subs_treemap_page($reporter, "subs-treemap-excl.html",
870 "Subroutine Exclusive Time Treemap", sub { shift->excl_time });
871 print $fh q{<br/>You can view a <a href="subs-treemap-excl.html">treemap of subroutine exclusive time</a>, grouped by package.<br/>};
872 }
873 else {
874 print $fh q{<br/>(Can't create visual treemap of subroutine exclusive times without the <a href="http://metacpan.org/release/JSON-MaybeXS/">JSON::MaybeXS</a> module.)<br/>};
875 }
876
877 if (not $opt_minimal) {
878 output_subs_callgraph_dot_file($reporter, "packages-callgraph.dot", undef, 1);
879 print $fh q{NYTProf also generates call-graph files in }
880 .q{<a href="http://en.wikipedia.org/wiki/Graphviz">Graphviz</a> format: }
881 .q{<a href="packages-callgraph.dot">inter-package calls</a>};
882 output_subs_callgraph_dot_file($reporter, "subs-callgraph.dot", undef, 0);
883 print $fh q{, <a href="subs-callgraph.dot">all inter-subroutine calls</a>};
884 print $fh q{ (probably too complex to render easily)}
885 if $all_subs > 200; # arbitrary
886 print $fh q{.<br/>};
887 }
888
889 print $fh q{<br/>You can hover over some table cells and headings to view extra information.};
890 print $fh q{<br/>Some table column headings can be clicked on to sort the table by that column.};
891 print $fh q{<br/>};
892
893 output_file_table($fh, $profile, 1);
894
895 my $footer = get_footer($profile);
896 print $fh "</div>$footer</body></html>";
897 close $fh;
898 }
899
900
901 # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
902 # treemap subs
903
904 sub js_for_new_treemap {
905 my ($name, $new_args, $tree_data) = @_;
906
907 return '' unless $has_json;
908
909 my $default_new_args = {
910 titleHeight => 0, # no titles
911 addLeftClickHandler => 1, # zoom in
912 #addRightClickHandler => 1, # zoom out (XXX but disables right click menu)
913 offset => 0, # (0/2/4) extra padding around nested levels
914
915 Color => {
916 allow => 1,
917 # value range for the $color property
918 minValue => 0,
919 maxValue => scalar @treemap_colors,
920 # corresponding color range [R,G,B]:
921 minColorValue => [0, 255, 50],
922 maxColorValue => [255, 0, 50],
923 },
924
925 Tips => {
926 allow => 1,
927 offsetX => 20,
928 offsetY => 20,
929 },
930
931 selectPathOnHover => 1, # adds "over-<foo>" css class to elements
932 };
933 exists $new_args->{$_} or $new_args->{$_} = $default_new_args->{$_}
934 for keys %$default_new_args;
935
936 my $new_args_json = encode_json($new_args);
937 my $tree_data_json = encode_json($tree_data);
938
939 my $js = qq{
940 function init_$name() {
941 var tm_args = $new_args_json;
942
943 //This method is invoked when a DOM element is created.
944 //Its useful to set DOM event handlers here or manipulate
945 //the DOM Treemap nodes.
946 tm_args.onCreateElement = function(content, tree, isLeaf, leaf){
947 //Add background image for cushion effect
948 if(isLeaf) {
949 var style = leaf.style,
950 width = parseInt(style.width) - 2,
951 height = parseInt(style.height) - 2;
952 // don't add gradient if too small to be worth the cost
953 if (width < 10 || height < 10) { // is narrow
954 if (width < 50 && height < 50) // is small
955 return;
956 }
957 leaf.innerHTML = tree.name +
958 "<img src=\\"js/jit/gradient-cushion1.png\\" " +
959 " style=\\"position:absolute;top:0;left:0;width:" +
960 width+"px;height:" + height+"px;\\" />";
961 style.width = width + "px";
962 style.height = height + "px";
963 }
964 };
965
966 // add content to the tooltip when a node is hovered
967 // move to separate function later
968 tm_args.Tips.onShow = function(tip, node, isLeaf, domElement) {
969 tip.innerHTML = node.data.tip;
970 };
971
972 TM.Squarified.implement({
973 'onLeftClick': function(elem) { // zoom in one level
974 //if is leaf
975 var node = TreeUtil.getSubtree(this.tree, elem.parentNode.id);
976 if(node.children && node.children.length == 0) {
977 var oldparent = node, newparent = node;
978 while(newparent.id != this.shownTree.id) {
979 oldparent = newparent;
980 newparent = TreeUtil.getParent(this.tree, newparent.id);
981 }
982 this.view(oldparent.id);
983 } else {
984 this.enter(elem);
985 }
986 }
987 });
988
989 TM.Squarified.implement({
990 createBox: function(json, coord, html) {
991 if((coord.width * coord.height > 1) && json.data.\$area > 0) {
992 if(!this.leaf(json))
993 var box = this.headBox(json, coord) + this.bodyBox(html, coord);
994 else
995 var box = this.leafBox(json, coord);
996 return this.contentBox(json, coord, box);
997 } else {
998 return ""; //return empty string
999 }
1000 }
1001 });
1002
1003 var $name = new TM.Squarified(tm_args);
1004
1005 var json = $tree_data_json;
1006
1007 $name.loadJSON(json);
1008 }
1009 };
1010 return $js;
1011 }
1012
1013
1014 sub pl { # dumb but sufficient pluralization
1015 my ($fmt, $n) = @_;
1016 sprintf $fmt.($n == 1 ? "" : "s"), $n;
1017 }
1018
1019
1020 sub package_subinfo_map_to_tm_data {
1021 my ($package_tree_subinfo_map, $area_sub) = @_;
1022
1023 my $sub_tip_html = sub {
1024 my $si = shift;
1025 my @html;
1026 push @html, sprintf "<p><b>%s</b></p><p>", $si->subname;
1027
1028 push @html, sprintf "Called %s from %s in %s",
1029 pl("%d time", $si->calls),
1030 pl("%d place", scalar $si->caller_places),
1031 pl("%d file", scalar $si->caller_fids);
1032
1033 my $total_time = $si->profile->{attribute}{profiler_duration};
1034 my $incl_time = $si->incl_time;
1035 push @html, sprintf "Inclusive time: %s, %.2f%%",
1036 fmt_time($incl_time), $total_time ? $incl_time/$total_time*100 : 0;
1037 my $excl_time = $si->excl_time;
1038 push @html, sprintf "Exclusive time: %s, %.2f%%",
1039 fmt_time($excl_time), $total_time ? $excl_time/$total_time*100 : 0
1040 if $excl_time ne $incl_time;
1041
1042 if (my $mrd = $si->recur_max_depth) {
1043 push @html, sprintf "Recursion: max depth %d, recursive inclusive time %s",
1044 $mrd, fmt_time($si->recur_incl_time);
1045 }
1046
1047 return join("<br />", @html)."</p>";
1048 };
1049
1050 my $leaf_data_sub = sub {
1051 my ($subinfo, $area_from, $color) = @_;
1052 my $data = {
1053 '$area' => $area_from->($subinfo),
1054 '$color' => $color,
1055 tip => $sub_tip_html->($subinfo),
1056 map({ $_ => $subinfo->$_() }
1057 qw(subname incl_time excl_time))
1058 };
1059 return $data;
1060 };
1061
1062 our $nid;
1063 my $node_mapper;
1064 $node_mapper = sub {
1065 my ($k, $v, $title) = @_;
1066 $title = ($title) ? '::'.$k : $k;
1067
1068 my $n = {
1069 id => "n".++$nid,
1070 name => $title,
1071 };
1072
1073 my @kids;
1074 for my $pkg_elem (keys %$v) {
1075 my $infos = $v->{$pkg_elem};
1076
1077 if (ref $infos eq 'HASH') { # recurse into subpackages
1078 push @kids, $node_mapper->($pkg_elem, $infos, $title);
1079 next;
1080 }
1081
1082 # subs within this package
1083 our $color_seqn; # all subs in pkg get same color
1084 my $color = $treemap_colors[ $color_seqn++ % @treemap_colors ];
1085
1086 for my $info (@$infos) {
1087
1088 # don't bother including subs that don't have any data
1089 # (unless we've not got any subs yet, to avoid problems elsewhere)
1090 next if $area_sub->($info) <= 0;
1091
1092 push @kids, {
1093 id => ++$nid."-".$info->subname,
1094 name => $info->subname_without_package,
1095 data => $leaf_data_sub->($info, $area_sub, $color),
1096 children => [],
1097 };
1098 }
1099 }
1100
1101 $n->{data}{'$area'} = (@kids) ? sum(map { $_->{data}{'$area'} } @kids) : 0
1102 if not defined $n->{data}{'$area'};
1103 $n->{children} = \@kids;
1104
1105 return $n;
1106 };
1107
1108 return $node_mapper->('', $package_tree_subinfo_map, '');
1109 }
1110
1111
1112 sub output_treemap_code {
1113 my (%spec) = @_;
1114 my $fh = $spec{fh};
1115 my $tm_id = 'tm'.$spec{id};
1116 my $root_id = 'infovis'.$spec{id};
1117
1118 my $treemap_data = $spec{get_data}->();
1119 $treemap_data->{name} = $spec{title} if $spec{title};
1120
1121 my $tm_js = js_for_new_treemap($tm_id, { rootId => $root_id }, $treemap_data);
1122 print $fh qq{<script type="text/javascript">$tm_js\n</script>\n};
1123
1124 push @on_ready_js, qq{init_$tm_id(); };
1125 return $root_id;
1126 }
1127
1128
1129 sub output_subs_treemap_page {
1130 my ($r, $filename, $title, $area_sub) = @_;
1131 my $profile = $reporter->{profile};
1132
1133 open(my $fh, '>', "$opt_out/$filename")
1134 or croak "Unable to open file $opt_out/$filename: $!";
1135
1136 $title ||= "Subroutine Time Treemap";
1137 print $fh get_html_header("$title - NYTProf", { add_jit => "Treemap" });
1138 print $fh get_page_header( profile => $profile, title => $title);
1139
1140 my @specs;
1141 push @specs, {
1142 id => 1,
1143 title => "Treemap of subroutine exclusive time",
1144 get_data => sub {
1145 package_subinfo_map_to_tm_data(
1146 $profile->package_subinfo_map(0,1),
1147 $area_sub || sub { shift->excl_time }, 0);
1148 }
1149 };
1150
1151 my @root_ids;
1152 for my $spec (@specs) {
1153 push @root_ids, output_treemap_code(
1154 fh => $fh,
1155 profile => $profile,
1156 %$spec
1157 );
1158 }
1159
1160 print $fh qq{<div class="vis_header"><br/>Boxes represent time spent in a subroutine. Coloring represents packages. Click to drill-down into package hierarchy, reload page to reset.</div>\n};
1161 print $fh qq{<div id="infovis">\n};
1162 print $fh qq{<br /><div id="$_"></div>\n} for @root_ids;
1163 print $fh qq{</div>\n};
1164
1165 my $footer = get_footer($profile);
1166 print $fh "$footer</body></html>";
1167 close $fh;
1168 }
1169
1170
1171 # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
1172
1173 sub output_subs_callgraph_dot_file {
1174 my ($r, $filename, $sub_filter, $only_show_packages) = @_;
1175 my $profile = $reporter->{profile};
1176 my $subinfos = $profile->subname_subinfo_map;
1177
1178 my $dot_file = "$opt_out/$filename";
1179 open my $fh, '>', $dot_file
1180 or croak "Unable to open file $dot_file: $!";
1181
1182 my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);
1183 my $dotnode = sub {
1184 my $name = shift;
1185 $name =~ s/$inc_path_regex//;
1186 $name =~ s/"/\\"/g;
1187 return '"'.$name.'"';
1188 };
1189
1190 print $fh "digraph {\n"; # }
1191 print $fh "graph [overlap=false]\n"; # target="???", URL="???"
1192
1193 # gather link info
1194 my %sub2called_by;
1195 for my $subname (keys %$subinfos) {
1196 my $si = $subinfos->{$subname};
1197 next unless $si->calls; # skip subs never called
1198
1199 next if $sub_filter and not $sub_filter->($si, undef);
1200
1201 my $called_by_subnames = $si->called_by_subnames;
1202 if (!%$called_by_subnames) {
1203 warn sprintf "%s has no caller subnames but a call count of %d\n",
1204 $subname, $si->calls;
1205 next;
1206 }
1207
1208 if ($sub_filter) {
1209 my @delete = grep { !$sub_filter->($si, $_) } keys %$called_by_subnames;
1210 if (@delete) {
1211 # shallow copy so we can edit it safely
1212 $called_by_subnames = { %$called_by_subnames };
1213 delete @{$called_by_subnames}{@delete};
1214 }
1215 next if !keys %$called_by_subnames;
1216 }
1217
1218 $sub2called_by{$subname} = $called_by_subnames;
1219 }
1220
1221 # list of all subs to be included in graph (has duplicates)
1222 my %pkg_subs;
1223 for (keys %sub2called_by, map { keys %$_ } values %sub2called_by) {
1224 m/^(.*)::(.*)?$/ or warn "Strange sub name '$_'";
1225 $pkg_subs{$1}{$_} = $sub2called_by{$_} || {};
1226 }
1227
1228 #stmt : node_stmt | edge_stmt | attr_stmt | ID '=' ID | subgraph
1229 #attr_stmt : (graph | node | edge) attr_list
1230 #attr_list : '[' [ a_list ] ']' [ attr_list ]
1231 #a_list : ID [ '=' ID ] [ ',' ] [ a_list ]
1232 #subgraph : [ subgraph [ ID ] ] '{' stmt_list '}'
1233
1234 if ($only_show_packages) {
1235 my %once;
1236 # XXX many shapes cause v.large graphs with nodes v.far apart
1237 # when using neato (energy minimized) possibly a neato bug
1238 # some shapes, like doublecircle seem to avoid the problem.
1239 print $fh "node [shape=doublecircle];\n";
1240 while ( my ($pkg, $subs) = each %pkg_subs ) {
1241 my @called_by = map { keys %$_ } values %$subs;
1242
1243 for my $called_by (@called_by) {
1244 (my $called_by_pkg = $called_by) =~ s/^(.*)::.*?$/$1/;
1245 my $link = sprintf qq{%s -> %s;\n},
1246 $dotnode->("$called_by_pkg"), $dotnode->("$pkg");
1247 $once{$link} = 1;
1248 }
1249
1250 }
1251 print $fh $_ for keys %once;
1252
1253 }
1254 else {
1255
1256 # output nodes and gather link info
1257 while ( my ($pkg, $pkg_subs) = each %pkg_subs) {
1258 (my $pkgmangled = $pkg) =~ s/\W+/_/g;
1259
1260 # node_stmt: node_id [ attr_list ]
1261 printf $fh "subgraph cluster_%s {\n", $pkgmangled; # }
1262 printf $fh "\tlabel=%s;\n", $dotnode->($pkg);
1263
1264 for my $subname (keys %$pkg_subs) {
1265 # node_stmt: node_id [ attr_list ]
1266 #printf $fh qq{\tnode [ %s ]}, ...
1267 printf $fh qq{\t%s;\n}, $dotnode->($subname);
1268 }
1269
1270 # { - just to balance the brace below
1271 printf $fh "}\n";
1272 }
1273
1274 while ( my ($subname, $called_by_subnames) = each %sub2called_by ) {
1275
1276 for my $called_by (keys %$called_by_subnames) {
1277 # edge_stmt : (node_id | subgraph) edgeRHS [ attr_list ]
1278 # edgeRHS : edgeop (node_id | subgraph) [ edgeRHS ]
1279 printf $fh qq{%s -> %s;\n},
1280 $dotnode->($called_by), $dotnode->($subname);
1281 }
1282
1283 }
1284 }
1285
1286 print $fh "}\n";
1287
1288 close $fh;
1289 #system("open '$dot_file'"); die 1;
1290
1291 return;
1292 }
1293
1294 # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
1295
1296 sub output_js_files {
1297 my ($profile) = @_;
1298 # find the js, gif, css etc files installed with Devel::NYTProf
1299 (my $lib = $INC{"Devel/NYTProf/Data.pm"}) =~ s/\/Data\.pm$//;
•1300 $lib = '/usr/share/perl5/Devel/NYTProf';
1301 _copy_dir("$lib/js", "$opt_out/js");
1302 }
1303
1304 sub _copy_dir {
1305 my ($srcdir, $dstdir) = @_;
1306 mkdir $dstdir or die "Can't create $dstdir directory: $!\n"
1307 unless -d $dstdir;
1308 for my $src (glob("$srcdir/*")) {
1309 (my $name = $src) =~ s{.*/}{};
1310 next if $name =~ m/^\./; # skip . and .. etc
1311 my $dstname = "$dstdir/$name";
1312 if (not -f $src) {
1313 _copy_dir($src, $dstname) if -d $src; # recurse
1314 next; # skip non-ordinary-files
1315 }
1316 unlink $dstname;
1317 copy($src, $dstname)
1318 or warn "Unable to copy $src to $dstname: $!";
1319 }
1320 }
1321
1322
1323 sub open_browser_on {
1324 my $index = shift;
1325
1326 my $exit_code = eval { require Browser::Open; Browser::Open::open_browser($index, 1); };
1327 return if defined($exit_code) && $exit_code == 0;
1328 warn "$@\n" if $@ && $opt_debug;
1329
1330 return if eval { require ActiveState::Browser; ActiveState::Browser::open($index); 1 };
1331 warn "$@\n" if $@ && $opt_debug && $^O eq "MSWin32";
1332
1333
1334 my $BROWSER;
1335 if ($^O eq "MSWin32") {
1336 $BROWSER = "start %s";
1337 }
1338 elsif ($^O eq "darwin") {
1339 $BROWSER = "/usr/bin/open %s";
1340 }
1341 else {
1342 my @try;
1343 if ($ENV{BROWSER}) {
1344 push(@try, split(/:/, $ENV{BROWSER}));
1345 }
1346 else {
1347 push(@try, qw(firefox galeon mozilla opera netscape));
1348 }
1349 unshift(@try, "kfmclient") if $ENV{KDE_FULL_SESSION};
1350 unshift(@try, "gnome-open") if $ENV{GNOME_DESKTOP_SESSION_ID};
1351 unshift(@try, "xdg-open");
1352 for (grep { have_prog($_) } @try) {
1353 if ($_ eq "kfmclient") {
1354 $BROWSER = "$_ openURL %s";
1355 }
1356 elsif ($_ eq "gnome-open" || $_ eq "opera") {
1357 $BROWSER = "$_ %s";
1358 }
1359 else {
1360 $BROWSER = "$_ %s &";
1361 }
1362 last;
1363 }
1364 }
1365 if ($BROWSER) {
1366 (my $cmd = $BROWSER) =~ s/%s/"$index"/;
1367 warn "Running $cmd\n" if $opt_debug;
1368 system($cmd);
1369 }
1370 else {
1371 warn "Don't know how to invoke your web browser.\nPlease visit $index yourself!\n";
1372 }
1373 }
1374
1375
1376 sub have_prog {
1377 my $prog = shift;
1378 for (split($Config{path_sep}, $ENV{PATH})) {
1379 return 1 if -x "$_/$prog";
1380 }
1381 return 0;
1382 }
1383
1384
1385 sub output_file_table {
1386 my ($fh, $profile, $add_totals) = @_;
1387
1388 # generate time-sorted sections for files
1389 print $fh qq{
1390 <table id="filestable" border="1" cellspacing="0" class="tablesorter floatHeaders">
1391 <caption>Source Code Files &mdash; ordered by exclusive time then name</caption>
1392 };
1393 print $fh qq{
1394 <thead><tr class="index">
1395 <th>Stmts</th><th>Exclusive<br />Time</th>
1396 <th>Reports</th><th>Source File</th>
1397 </tr></thead>
1398 <tbody>
1399 };
1400
1401 my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);
1402
1403 my $allTimes = $profile->{attribute}{total_stmts_duration};
1404 my $allCalls = $profile->{attribute}{total_stmts_measured}
1405 - $profile->{attribute}{total_stmts_discounted};
1406 # file in which sawampersand was noted during profiling
1407 my $sawampersand_fi = $profile->fileinfo_of($profile->{attribute}{sawampersand_fid}, 1);
1408
1409 my (@t_stmt_exec, @t_stmt_time);
1410 my @fis = $profile->noneval_fileinfos;
1411 @fis = sort { $b->meta->{'time'} <=> $a->meta->{'time'} } @fis;
1412
1413 my $dev_time = calculate_median_absolute_deviation([map { scalar $_->meta->{'time'} } @fis], 1);
1414
1415 foreach my $fi (@fis) {
1416 my $meta = $fi->meta;
1417 my $fid = $fi->fid;
1418 my @extra;
1419 my $css_class = 'index';
1420
1421 # The stats in this table include rolled up sums of nested evals.
1422
1423 my ($eval_stmts, $eval_time) = (0,0);
1424 if (my @has_evals = $fi->has_evals(1)) {
1425 my $n_evals = scalar @has_evals;
1426 my $msg = sprintf "including %d string eval%s", $n_evals, ($n_evals>1) ? "s" : "";
1427 if (my @nested = grep { $_->eval_fid != $fid } @has_evals) {
1428 $msg .= sprintf ": %d direct plus %d nested",
1429 $n_evals-@nested, scalar @nested;
1430 }
1431 push @extra, $msg;
1432 $eval_stmts = sum(map { $_->sum_of_stmts_count } @has_evals);
1433 $eval_time = sum(map { $_->sum_of_stmts_time } @has_evals);
1434 }
1435 # is this file one where we sawampersand (or contains an eval that is)?
1436 if ($sawampersand_fi
1437 && $] < 5.017008
1438 && $fi == ($sawampersand_fi->outer || $sawampersand_fi)
1439 ) {
1440 my $in_eval = ($fi == $sawampersand_fi)
1441 ? 'here'
1442 : sprintf q{<a %s>in eval here</a>}, $reporter->href_for_file($sawampersand_fi, undef, 'line');
1443 push @extra, sprintf qq{variables that impact regex performance for whole application seen $in_eval},
1444 $css_class = "warn $css_class";
1445 }
1446
1447 print $fh qq{<tr class="$css_class">};
1448
1449 my $stmts = $meta->{'calls'} + $eval_stmts;
1450 print $fh determine_severity($stmts, undef, 0,
1451 ($allCalls) ? sprintf("%.1f%%", $stmts/$allCalls*100) : ''
1452 );
1453 push @t_stmt_exec, $stmts;
1454
1455 my $time = $meta->{'time'} + $eval_time;
1456 print $fh determine_severity($time, $dev_time, 1,
1457 ($allTimes) ? sprintf("%.1f%%", $time/$allTimes*100) : ''
1458 );
1459 push @t_stmt_time, $time;
1460
1461
1462 my %levels = reverse %{$profile->get_profile_levels};
1463 my $rep_links = join '&nbsp;&bull;&nbsp;', map {
1464 sprintf(qq{<a %s>%s</a>}, $reporter->href_for_file($fi, undef, $_), $_)
1465 } grep { $levels{$_} } qw(line block sub);
1466 print $fh "<td>$rep_links</td>";
1467
1468 print $fh sprintf q{<td><a name="f%s" title="%s">%s</a> %s</td>},
1469 $fi->fid, $fi->abs_filename, $fi->filename_without_inc,
1470 (@extra) ? sprintf("(%s)", join "; ", @extra) : "";
1471 print $fh "</tr>\n";
1472 }
1473 print $fh "</tbody>\n";
1474
1475 if ($add_totals) {
1476 print $fh "<tfoot>\n";
1477 my $stats_fmt =
1478 qq{<tr class="index"><td class="n">%s</td><td class="n">%s</td><td colspan="2" style="font-style: italic">%s</td></tr>};
1479 my $t_notes = "";
1480 my $stmt_time_diff = $allTimes - sum(@t_stmt_time);
1481 if (sum(@t_stmt_exec) != $allCalls or $stmt_time_diff > 0.001) {
1482 $stmt_time_diff = ($stmt_time_diff > 0.001)
1483 ? sprintf(" and %s", fmt_time($stmt_time_diff)) : "";
1484 $t_notes = sprintf "(%d statements%s are unaccounted for)",
1485 $allCalls - sum(@t_stmt_exec), $stmt_time_diff;
1486 }
1487 print $fh sprintf $stats_fmt, fmt_float(sum(@t_stmt_exec)), fmt_time(sum(@t_stmt_time)),
1488 "Total $t_notes"
1489 if @t_stmt_exec > 1 or $t_notes;
1490
1491 if (@t_stmt_exec > 1) {
1492 print $fh sprintf $stats_fmt,
1493 int(fmt_float(sum(@t_stmt_exec) / @t_stmt_exec)),
1494 fmt_time( sum(@t_stmt_time) / @t_stmt_time), "Average";
1495 print $fh sprintf $stats_fmt, '', fmt_time( $dev_time->[1]), "Median";
1496 print $fh sprintf $stats_fmt, '', fmt_float($dev_time->[0]), "Deviation"
1497 if $dev_time->[0];
1498 }
1499
1500 print $fh "</tfoot>\n";
1501 }
1502
1503 print $fh '</table>';
1504 push @on_ready_js, q{
1505 $("#filestable").tablesorter({
1506 sortList: [[1,1],[3,1]],
1507 headers: {
1508 1: { sorter: 'fmt_time' },
1509 2: { sorter: false }
1510 }
1511 });
1512
1513 $(".floatHeaders").each( function(){ $(this).floatThead(); } );
1514
1515 show_fragment_target();
1516 $(window).on('hashchange', function(e){
1517 show_fragment_target();
1518 });
1519 };
1520
1521 return "";
1522 }
1523
1524 # calculates how good or bad the time is for a file based on the others
1525 sub determine_severity {
1526 my $val = shift;
1527 return "<td></td>" unless defined $val;
1528 my $stats = shift; # @_[3] is like arrayref (deviation, mean)
1529 my $is_time = shift;
1530 my $title = shift;
1531
1532 # normalize the width/precision so that the tables look good.
1533 my $fmt_val = ($is_time)
1534 ? fmt_time($val)
1535 : fmt_float($val, NUMERIC_PRECISION);
1536
1537 my $class;
1538 if (defined $stats) {
1539
1540 my $devs = ($val - $stats->[1]); #stats->[1] is the mean.
1541 $devs /= $stats->[0] if $stats->[0]; # no divide by zero when all values equal
1542
1543 if ($devs < 0) { # fast
1544 $class = 'c3';
1545 }
1546 elsif ($devs < SEVERITY_GOOD) {
1547 $class = 'c3';
1548 }
1549 elsif ($devs < SEVERITY_BAD) {
1550 $class = 'c2';
1551 }
1552 elsif ($devs < SEVERITY_SEVERE) {
1553 $class = 'c1';
1554 }
1555 else {
1556 $class = 'c0';
1557 }
1558 }
1559 else {
1560 $class = 'n';
1561 }
1562
1563 if ($title) {
1564 $title = (ref $title) ? $$title : _escape_html($title);
1565 $fmt_val = qq{<span title="$title">$fmt_val</span>};
1566 }
1567
1568 return qq{<td class="$class">$fmt_val</td>};
1569 }
1570
1571
1572 # return an html string with buttons for switching between profile levels of detail
1573 sub get_level_buttons {
1574 my $mode_ref = shift;
1575 my $file = shift;
1576 my $level = shift;
1577
1578 my $html = join '&emsp;&bull;&emsp;', map {
1579 my $mode = $mode_ref->{$_};
1580
1581 if ($mode eq $level) {
1582 qq{<span class="mode_btn mode_btn_selected">$mode view</span>};
1583 }
1584 else {
1585 my $mode_file = $file;
1586
1587 # replace the mode specifier in the output file name -- file-name-MODE.html
1588 $mode_file =~ s/(.*-).*?\.html/$1$mode.html/o;
1589
1590 qq{<span class="mode_btn"><a href="$mode_file">$mode view</a></span>};
1591 }
1592 } keys %$mode_ref;
1593
1594 return qq{<span>&laquo;&emsp;$html&emsp;&raquo;</span>};
1595 }
1596
1597
1598 sub get_footer {
1599 my ($profile) = @_;
1600 my $version = $Devel::NYTProf::Core::VERSION;
1601
1602 my $js = '';
1603 if (@on_ready_js) {
1604 # XXX I've no idea why this workaround is needed (or works).
1605 # without it the file table on the index page isn't sortable
1606 @on_ready_js = reverse @on_ready_js;
1607
1608 $js = sprintf q{
1609 <script type="text/javascript">
1610 $(document).ready(function() { %s } );
1611 </script>
1612 }, join("\n", '', @on_ready_js, '');
1613 @on_ready_js = ();
1614 };
1615
1616 # spacing so links to #line near can put right line at top near the bottom of the report
1617 my $spacing = "<br />" x 10;
1618 return qq{
1619 $js
1620 <div class="footer">Report produced by the
1621 <a href="http://metacpan.org/release/Devel-NYTProf/">NYTProf $version</a>
1622 Perl profiler, developed by
1623 <a href="http://www.linkedin.com/in/timbunce">Tim Bunce</a> based on
1624 work by Adam Kaplan and Salvador Fandiño García.
1625 </div>
1626 $spacing
1627 };
1628 }
1629
1630 # returns the generic header string. Here only to make the code more readable.
1631 sub get_html_header {
1632 my $title = shift || "Profile Index - NYTProf";
1633 my $opts = shift || {};
1634
1635 $title = _escape_html($title);
1636
1637 my $html = <<EOD;
1638 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1639 <html xmlns="http://www.w3.org/1999/xhtml">
1640 EOD
1641 $html = "<html>" if $opts->{not_xhtml};
1642 $html .= <<EOD;
1643 <!--
1644 This file was generated by Devel::NYTProf version $Devel::NYTProf::Core::VERSION
1645 -->
1646 <head>
1647 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1648 <meta http-equiv="Content-Language" content="en-us" />
1649 <meta name="robots" content="noindex,nofollow" />
1650 <title>$title</title>
1651 EOD
1652
1653 $html .= qq{ <link rel="stylesheet" type="text/css" href="style.css" />\n}
1654 unless $opts->{skip_style};
1655
1656 if (my $css = $opts->{add_jit}) {
1657 $html .= qq{ <link rel="stylesheet" type="text/css" href="js/jit/$css.css" />\n};
1658 $html .= qq{ <script language="JavaScript" src="js/jit/jit.js"></script>\n};
1659 }
1660
1661 $html .= <<'EOD' unless $opts->{skip_jquery};
1662 <script type="text/javascript" src="js/jquery-min.js"></script>
1663
1664 <script type="text/javascript" src="js/jquery.floatThead.min.js"></script>
1665 <script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
1666 <link rel="stylesheet" type="text/css" href="js/style-tablesorter.css" />
1667 <script type="text/javascript">
1668 // when a column is first clicked on to sort it, use descending order
1669 // XXX doesn't seem to work (and not just because the tablesorter formatSortingOrder() is broken)
1670 $.tablesorter.defaults.sortInitialOrder = "desc";
1671 // add parser through the tablesorter addParser method
1672 $.tablesorter.addParser({
1673 id: 'fmt_time', // name of this parser
1674 is: function(s) {
1675 return false; // return false so this parser is not auto detected
1676 },
1677 format: function(orig) { // format data for normalization
1678 // console.log(orig);
1679 var val = orig.replace(/ns/,'');
1680 if (val != orig) { return val / (1000*1000*1000); }
1681 val = orig.replace(/[µ\xB5]s/,''); /* micro */
1682 if (val != orig) { return val / (1000*1000); }
1683 val = orig.replace(/ms/,'');
1684 if (val != orig) { return val / (1000); }
1685 val = orig.replace(/([0-9])s/,"$1");
1686 if (val != orig) { return val; }
1687 if (orig == '0') { return orig; }
1688 var non_number = orig.replace(/^[-+]?[0-9.]+/, '', 'g');
1689 console.log('no match for fmt_time of '+orig+' (units:'+non_number+' charCodeAt0:'+non_number.charCodeAt(0)+')');
1690 return orig;
1691 },
1692 type: 'numeric' // set type, either numeric or text
1693 });
1694
1695 function show_fragment_target() {
1696 var tgt = $(':target');
1697 var table = tgt.closest('table.floatHeaders');
1698 if( tgt.is('a') && table.is('table.floatHeaders') )
1699 {
1700 var cury = $(window).scrollTop();
1701 var fhYPos = table.prev('.floatThead-container').offset().top;
1702 var thHeight = table.find('thead').first().height();
1703 var tYPos = parseInt($(':target').closest('tr').position().top);
1704 if( tYPos < (fhYPos + thHeight) )
1705 {
1706 $(window).scrollTop(
1707 tYPos - (thHeight)
1708 );
1709 }
1710 }
1711 }
1712 </script>
1713 EOD
1714 $html .= $opts->{head_epilogue} if $opts->{head_epilogue};
1715
1716 $html .= <<EOD;
1717 </head>
1718 EOD
1719
1720 return $html;
1721 }
1722
1723 sub get_page_header {
1724 my %args = @_;
1725 my ($profile, $head1, $head2, $right1, $right2, $skip_link_to_index) = (
1726 $args{profile}, $args{title}, $args{subtitle},
1727 $args{title2}, $args{subtitle2}, $args{skip_link_to_index}
1728 );
1729
1730 $head2 ||= qq{<br />For ${ \($profile->{attribute}{application}) }};
1731 $right1 ||= "&nbsp;";
1732 $right2 ||= "Run on ${ \scalar localtime($profile->{attribute}{basetime}) }<br />Reported on "
1733 . localtime(time);
1734
1735 my $back_link = q//;
1736 unless ($skip_link_to_index) {
1737 $back_link = qq{<div class="header_back">
1738 <a href="index.html">&larr; Index</a>
1739 </div>};
1740 }
1741
1742 my @body_attribs;
1743 push @body_attribs, qq{onload="$args{body_onload}"} if $args{body_onload};
1744 my $body_attribs = join "; ", @body_attribs;
1745
1746 return qq{<body $body_attribs>
1747 <div class="header" style="position: relative; overflow-x: hidden; overflow-y: hidden; z-index: 0; ">
1748 $back_link
1749 <div class="headerForeground" style="float: left">
1750 <span class="siteTitle">$head1</span>
1751 <span class="siteSubtitle">$head2</span>
1752 </div>
1753 <div class="headerForeground" style="float: right; text-align: right">
1754 <span class="siteTitle">$right1</span>
1755 <span class="siteSubtitle">$right2</span>
1756 </div>
1757 <div style="position: absolute; left: 0px; top: 0%; width: 100%; height: 101%; z-index: -1; background-color: rgb(17, 136, 255); "></div>
1758 <div style="position: absolute; left: 0px; top: 2%; width: 100%; height: 99%; z-index: -1; background-color: rgb(16, 134, 253); "></div>
1759 <div style="position: absolute; left: 0px; top: 4%; width: 100%; height: 97%; z-index: -1; background-color: rgb(16, 133, 252); "></div>
1760 <div style="position: absolute; left: 0px; top: 6%; width: 100%; height: 95%; z-index: -1; background-color: rgb(15, 131, 250); "></div>
1761 <div style="position: absolute; left: 0px; top: 8%; width: 100%; height: 93%; z-index: -1; background-color: rgb(15, 130, 249); "></div>
1762 <div style="position: absolute; left: 0px; top: 10%; width: 100%; height: 91%; z-index: -1; background-color: rgb(15, 129, 248); "></div>
1763 <div style="position: absolute; left: 0px; top: 12%; width: 100%; height: 89%; z-index: -1; background-color: rgb(14, 127, 246); "></div>
1764 <div style="position: absolute; left: 0px; top: 14%; width: 100%; height: 87%; z-index: -1; background-color: rgb(14, 126, 245); "></div>
1765 <div style="position: absolute; left: 0px; top: 16%; width: 100%; height: 85%; z-index: -1; background-color: rgb(14, 125, 244); "></div>
1766 <div style="position: absolute; left: 0px; top: 18%; width: 100%; height: 83%; z-index: -1; background-color: rgb(13, 123, 242); "></div>
1767 <div style="position: absolute; left: 0px; top: 20%; width: 100%; height: 81%; z-index: -1; background-color: rgb(13, 122, 241); "></div>
1768 <div style="position: absolute; left: 0px; top: 22%; width: 100%; height: 79%; z-index: -1; background-color: rgb(13, 121, 240); "></div>
1769 <div style="position: absolute; left: 0px; top: 24%; width: 100%; height: 77%; z-index: -1; background-color: rgb(12, 119, 238); "></div>
1770 <div style="position: absolute; left: 0px; top: 26%; width: 100%; height: 75%; z-index: -1; background-color: rgb(12, 118, 237); "></div>
1771 <div style="position: absolute; left: 0px; top: 28%; width: 100%; height: 73%; z-index: -1; background-color: rgb(12, 116, 235); "></div>
1772 <div style="position: absolute; left: 0px; top: 30%; width: 100%; height: 71%; z-index: -1; background-color: rgb(11, 115, 234); "></div>
1773 <div style="position: absolute; left: 0px; top: 32%; width: 100%; height: 69%; z-index: -1; background-color: rgb(11, 114, 233); "></div>
1774 <div style="position: absolute; left: 0px; top: 34%; width: 100%; height: 67%; z-index: -1; background-color: rgb(11, 112, 231); "></div>
1775 <div style="position: absolute; left: 0px; top: 36%; width: 100%; height: 65%; z-index: -1; background-color: rgb(10, 111, 230); "></div>
1776 <div style="position: absolute; left: 0px; top: 38%; width: 100%; height: 63%; z-index: -1; background-color: rgb(10, 110, 229); "></div>
1777 <div style="position: absolute; left: 0px; top: 40%; width: 100%; height: 61%; z-index: -1; background-color: rgb(10, 108, 227); "></div>
1778 <div style="position: absolute; left: 0px; top: 42%; width: 100%; height: 59%; z-index: -1; background-color: rgb(9, 107, 226); "></div>
1779 <div style="position: absolute; left: 0px; top: 44%; width: 100%; height: 57%; z-index: -1; background-color: rgb(9, 106, 225); "></div>
1780 <div style="position: absolute; left: 0px; top: 46%; width: 100%; height: 55%; z-index: -1; background-color: rgb(9, 104, 223); "></div>
1781 <div style="position: absolute; left: 0px; top: 48%; width: 100%; height: 53%; z-index: -1; background-color: rgb(8, 103, 222); "></div>
1782 <div style="position: absolute; left: 0px; top: 50%; width: 100%; height: 51%; z-index: -1; background-color: rgb(8, 102, 221); "></div>
1783 <div style="position: absolute; left: 0px; top: 52%; width: 100%; height: 49%; z-index: -1; background-color: rgb(8, 100, 219); "></div>
1784 <div style="position: absolute; left: 0px; top: 54%; width: 100%; height: 47%; z-index: -1; background-color: rgb(7, 99, 218); "></div>
1785 <div style="position: absolute; left: 0px; top: 56%; width: 100%; height: 45%; z-index: -1; background-color: rgb(7, 97, 216); "></div>
1786 <div style="position: absolute; left: 0px; top: 58%; width: 100%; height: 43%; z-index: -1; background-color: rgb(7, 96, 215); "></div>
1787 <div style="position: absolute; left: 0px; top: 60%; width: 100%; height: 41%; z-index: -1; background-color: rgb(6, 95, 214); "></div>
1788 <div style="position: absolute; left: 0px; top: 62%; width: 100%; height: 39%; z-index: -1; background-color: rgb(6, 93, 212); "></div>
1789 <div style="position: absolute; left: 0px; top: 64%; width: 100%; height: 37%; z-index: -1; background-color: rgb(6, 92, 211); "></div>
1790 <div style="position: absolute; left: 0px; top: 66%; width: 100%; height: 35%; z-index: -1; background-color: rgb(5, 91, 210); "></div>
1791 <div style="position: absolute; left: 0px; top: 68%; width: 100%; height: 33%; z-index: -1; background-color: rgb(5, 89, 208); "></div>
1792 <div style="position: absolute; left: 0px; top: 70%; width: 100%; height: 31%; z-index: -1; background-color: rgb(5, 88, 207); "></div>
1793 <div style="position: absolute; left: 0px; top: 72%; width: 100%; height: 29%; z-index: -1; background-color: rgb(4, 87, 206); "></div>
1794 <div style="position: absolute; left: 0px; top: 74%; width: 100%; height: 27%; z-index: -1; background-color: rgb(4, 85, 204); "></div>
1795 <div style="position: absolute; left: 0px; top: 76%; width: 100%; height: 25%; z-index: -1; background-color: rgb(4, 84, 203); "></div>
1796 <div style="position: absolute; left: 0px; top: 78%; width: 100%; height: 23%; z-index: -1; background-color: rgb(3, 82, 201); "></div>
1797 <div style="position: absolute; left: 0px; top: 80%; width: 100%; height: 21%; z-index: -1; background-color: rgb(3, 81, 200); "></div>
1798 <div style="position: absolute; left: 0px; top: 82%; width: 100%; height: 19%; z-index: -1; background-color: rgb(3, 80, 199); "></div>
1799 <div style="position: absolute; left: 0px; top: 84%; width: 100%; height: 17%; z-index: -1; background-color: rgb(2, 78, 197); "></div>
1800 <div style="position: absolute; left: 0px; top: 86%; width: 100%; height: 15%; z-index: -1; background-color: rgb(2, 77, 196); "></div>
1801 <div style="position: absolute; left: 0px; top: 88%; width: 100%; height: 13%; z-index: -1; background-color: rgb(2, 76, 195); "></div>
1802 <div style="position: absolute; left: 0px; top: 90%; width: 100%; height: 11%; z-index: -1; background-color: rgb(1, 74, 193); "></div>
1803 <div style="position: absolute; left: 0px; top: 92%; width: 100%; height: 9%; z-index: -1; background-color: rgb(1, 73, 192); "></div>
1804 <div style="position: absolute; left: 0px; top: 94%; width: 100%; height: 7%; z-index: -1; background-color: rgb(1, 72, 191); "></div>
1805 <div style="position: absolute; left: 0px; top: 96%; width: 100%; height: 5%; z-index: -1; background-color: rgb(0, 70, 189); "></div>
1806 <div style="position: absolute; left: 0px; top: 98%; width: 100%; height: 3%; z-index: -1; background-color: rgb(0, 69, 188); "></div>
1807 <div style="position: absolute; left: 0px; top: 100%; width: 100%; height: 1%; z-index: -1; background-color: rgb(0, 68, 187); "></div>
1808 </div>\n};
1809 }
1810
1811 sub get_css {
1812 return <<'EOD';
1813 /* Stylesheet for Devel::NYTProf::Reader HTML reports */
1814
1815 /* You may modify this file to alter the appearance of your coverage
1816 * reports. If you do, you should probably flag it read-only to prevent
1817 * future runs from overwriting it.
1818 */
1819
1820 /* Note: default values use the color-safe web palette. */
1821 a { color: blue; }
1822 a:visited { color: #6d00E6; }
1823 a:hover { color: red; }
1824
1825 body { font-family: sans-serif; margin: 0px; background-color: white; color:#222; }
1826 .body_content { margin: 8px; }
1827
1828 .header { font-family: sans-serif; padding-left: 0.5em; padding-right: 0.5em; }
1829 .headerForeground { color: white; padding: 10px; padding-top: 50px; }
1830 .siteTitle { font-size: 2em; }
1831 .siteSubTitle { font-size: 1.2em; }
1832
1833 .header_back {
1834 position: absolute;
1835 padding: 10px;
1836 }
1837 .header_back > a:link,
1838 .header_back > a:visited {
1839 color: white;
1840 text-decoration: none;
1841 font-size: 0.75em;
1842 }
1843
1844 .jump_to_file {
1845 margin-top: 20px;
1846 }
1847
1848 .footer,
1849 .footer > a:link,
1850 .footer > a:visited {
1851 color: #cccccc;
1852 }
1853 .footer { margin: 30px; }
1854
1855 table {
1856 border-collapse: collapse;
1857 border-spacing: 0px;
1858 margin-top: 20px;
1859 }
1860 tr {
1861 text-align : center;
1862 vertical-align: top;
1863 }
1864 th,.h {
1865 background-color: #dddddd;
1866 border: solid 1px #666666;
1867 padding: 0em 0.4em 0em 0.4em;
1868 font-size:0.8em;
1869 }
1870 td {
1871 border: solid 1px #cccccc;
1872 padding: 0em 0.4em 0em 0.4em;
1873 }
1874 caption {
1875 background-color: #dddddd;
1876 text-align: left;
1877 white-space: pre;
1878 padding: 0.4em;
1879 }
1880
1881 .table_footer { color: gray; }
1882 .table_footer > a:link,
1883 .table_footer > a:visited { color: gray; }
1884 .table_footer > a:hover { color: red; }
1885
1886 .index { text-align: left; }
1887
1888 .mode_btn_selected {
1889 font-style: italic;
1890 }
1891
1892 /* subroutine dispatch table */
1893 .sub_name {
1894 text-align: left;
1895 font-family: monospace;
1896 white-space: pre;
1897 color: gray;
1898 }
1899
1900 /* source code */
1901 th.left_indent_header {
1902 padding-left: 15px;
1903 text-align: left;
1904 }
1905
1906 pre,.s {
1907 text-align: left;
1908 font-family: monospace;
1909 white-space: pre;
1910 }
1911 /* plain number */
1912 .n { text-align: right }
1913
1914 /* Classes for color-coding profiling information:
1915 * c0 : code not hit
1916 * c1 : coverage >= 75%
1917 * c2 : coverage >= 90%
1918 * c3 : path covered or coverage = 100%
1919 */
1920 .c0, .c1, .c2, .c3 { text-align: right; }
1921 .c0 { background-color: #ffb3b3; } /* red */
1922 .c1 { background-color: #ffd9b4; } /* orange */
1923 .c2 { background-color: #ffffB4; } /* yellow */
1924 .c3 { background-color: #B4ffB4; } /* green */
1925
1926 /* warnings */
1927 .warn {
1928 background-color: #FFFFAA;
1929 border: 0;
1930 width: 96%;
1931 text-align: center;
1932 padding: 5px 0;
1933 }
1934 .warn_title {
1935 background-color: #FFFFAA;
1936 border: 0;
1937 color: red;
1938 width: 96%;
1939 font-size: 2em;
1940 text-align: center;
1941 padding: 5px 0;
1942 }
1943
1944 /* summary of calls into and out of a sub */
1945 .calls {
1946 display: block;
1947 color: gray;
1948 padding-top: 5px;
1949 padding-bottom: 5px;
1950 text-decoration: none;
1951 }
1952 .calls:hover {
1953 background-color: #e8e8e8;
1954 color: black;
1955 }
1956 .calls a { color: gray; text-decoration: none; }
1957 .calls:hover a { color: black; text-decoration: underline; }
1958 .calls:hover a:hover { color: red; }
1959 /* give a little headroom to the summary of calls into a sub */
1960 .calls .calls_in { margin-top: 5px; }
1961
1962 .vis_header {
1963 text-align:center;
1964 font-style: italic;
1965 padding-top: 5px; color: gray;
1966 }
1967
1968 .flamegraph {
1969 margin: 20px 0px;
1970 }
1971
1972 EOD
1973 }
1974
1975 __END__
1976
1977 =head1 DESCRIPTION
1978
1979 Devel::NYTProf is a powerful feature-rich Perl source code profiler.
1980 See L<Devel::NYTProf> for details.
1981
1982 C<nytprofhtml> generates a set of html reports from a single data file
1983 generated by L<Devel::NYTProf>. (If your process forks you'll probably have
1984 multiple files. See L<Devel::NYTProf> and L<nytprofmerge>.)
1985
1986 The reports include dynamic runtime analysis wherein each line and each file
1987 is analyzed based on the performance of the other lines and files. As a
1988 result, you can quickly find the slowest module and the slowest line in a
1989 module. Slowness is measured in three ways: total calls, total time, and
1990 average time per call.
1991
1992 Coloring is based on absolute deviations from the median.
1993 See L<http://en.wikipedia.org/wiki/Median_absolute_deviation> for more details.
1994
1995 That might sound complicated, but in reality you can just run the command and
1996 enjoy your report!
1997
1998 =head1 COMMAND-LINE OPTIONS
1999
2000 =over 4
2001
2002 =item -f, --file <filename>
2003
2004 Specifies the location of the file generated by L<Devel::NYTProf>.
2005 Default: ./nytprof.out
2006
2007 =item -o, --out <dir>
2008
2009 The directory in which to place the generated report files. Default: ./nytprof/
2010
2011 =item -d, --delete
2012
2013 Purge any existing contents of the report output directory.
2014
2015 =item -l, --lib <dir>
2016
2017 Add a path to the beginning of @INC to help nytprofhtml find the source files
2018 used by the code. Should not be needed in practice.
2019
2020 =item --open
2021
2022 Make your web browser visit the report after it has been generated.
2023
2024 If this doesn't work well for you, try installing the L<Browser::Open> module.
2025
2026 =item -m, --minimal
2027
2028 Don't generate graphviz .dot files or block/sub-level reports.
2029
2030 =item --no-flame
2031
2032 Disable generation of the flamegraph on the index page.
2033 Also disables calculation of distinct call stacks that are used to produce the
2034 flamegraph.
2035
2036 =item -h, --help
2037
2038 Print the help message.
2039
2040 =back
2041
2042 =head1 SAMPLE OUTPUT
2043
2044 You can see a complete report for a large application at
2045 L<http://timbunce.github.io/devel-nytprof/sample-report/nytprof-20160319/index.html>
2046
2047 The report was generated by profiling L<perlcritic> 1.121 checking its own source code
2048 using perl v5.18.2.
2049
2050 =head1 DIAGNOSTICS
2051
2052 =head2 "Unable to open '... (autosplit into ...)'"
2053
2054 The profiled application executed code in a module that used L<AutoLoader> to
2055 load the code from a separate .al file. NYTProf automatically recognises this
2056 situation and tries to determine the 'parent' module file so it can associate
2057 the profile data with it. In order to do that the parent module file must
2058 already be 'known' to NYTProf, typically by already having some code profiled.
2059
2060 You're only likely to see this warning if you're using the C<start> option to
2061 start profiling after compile-time. The effect is that times spent in
2062 autoloaded subs won't be associated with the parent module file and you won't
2063 get annotated reports for them.
2064
2065 You can avoid this by using the default C<start=begin> option, or by ensuring
2066 you execute some non-autoloaded code in the parent module, while the profiler is
2067 running, before an autoloaded sub is called.
2068
2069
2070 =head2 Background
2071
2072 Subroutine-level profilers:
2073
2074 Devel::DProf | 1995-10-31 | ILYAZ
2075 Devel::AutoProfiler | 2002-04-07 | GSLONDON
2076 Devel::Profiler | 2002-05-20 | SAMTREGAR
2077 Devel::Profile | 2003-04-13 | JAW
2078 Devel::DProfLB | 2006-05-11 | JAW
2079 Devel::WxProf | 2008-04-14 | MKUTTER
2080
2081 Statement-level profilers:
2082
2083 Devel::SmallProf | 1997-07-30 | ASHTED
2084 Devel::FastProf | 2005-09-20 | SALVA
2085 Devel::NYTProf | 2008-03-04 | AKAPLAN
2086 Devel::Profit | 2008-05-19 | LBROCARD
2087
2088 Devel::NYTProf is a (now distant) fork of Devel::FastProf, which was itself an
2089 evolution of Devel::SmallProf.
2090
2091 Adam Kaplan took Devel::FastProf and added html report generation (based on
2092 Devel::Cover) and a test suite - a tricky thing to do for a profiler.
2093 Meanwhile Tim Bunce had been extending Devel::FastProf to add novel
2094 per-sub and per-block timing, plus subroutine caller tracking.
2095
2096 When Devel::NYTProf was released Tim switched to working on Devel::NYTProf
2097 because the html report would be a good way to show the extra profile data, and
2098 the test suite made development much easier and safer.
2099
2100 Then he went a little crazy and added a slew of new features, in addition to
2101 per-sub and per-block timing and subroutine caller tracking. These included the
2102 'opcode interception' method of profiling, ultra-fast and robust inclusive
2103 subroutine timing, doubling performance, plus major changes to html reporting
2104 to display all the extra profile call and timing data in richly annotated and
2105 cross-linked reports.
2106
2107 Steve Peters came on board along the way with patches for portability and to
2108 keep NYTProf working with the latest development Perl versions.
2109
2110 Adam's work is sponsored by The New York Times Co. L<http://open.nytimes.com>.
2111 Tim's work was partly sponsored by Shopzilla. L<http://www.shopzilla.com>.
2112
2113 =head1 SEE ALSO
2114
2115 Mailing list and discussion at L<http://groups.google.com/group/develnytprof-dev>
2116
2117 Public Github Repository and hacking instructions at L<https://github.com/timbunce/devel-nytprof/>
2118
2119 L<Devel::NYTProf>,
2120 L<Devel::NYTProf::Reader>,
2121 L<nytprofcsv>
2122
2123 =head1 AUTHOR
2124
2125 B<Adam Kaplan>, C<< <akaplan at nytimes.com> >>.
2126 B<Tim Bunce>, L<http://blog.timbunce.org>.
2127 B<Steve Peters>, C<< <steve at fisharerojo.org> >>.
2128
2129 =head1 COPYRIGHT AND LICENSE
2130
2131 This program is free software; you can redistribute it and/or modify
2132 it under the same terms as Perl itself, either Perl version 5.8.8 or,
2133 at your option, any later version of Perl 5 you may have available.
2134
2135 =cut
2136
2137 # vim:ts=8:sw=4:expandtab