Debian Codegraph @

bin/nytprofhtml

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