Debian Codegraph @

bin/nytprofhtml

raw ◀ ▶
Source reconstructed at patch state 1 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 $lib = '/usr/share/perl5/Devel/NYTProf';
1300 _copy_dir("$lib/js", "$opt_out/js");
1301 }
1302
1303 sub _copy_dir {
1304 my ($srcdir, $dstdir) = @_;
1305 mkdir $dstdir or die "Can't create $dstdir directory: $!\n"
1306 unless -d $dstdir;
1307 for my $src (glob("$srcdir/*")) {
1308 (my $name = $src) =~ s{.*/}{};
1309 next if $name =~ m/^\./; # skip . and .. etc
1310 my $dstname = "$dstdir/$name";
1311 if (not -f $src) {
1312 _copy_dir($src, $dstname) if -d $src; # recurse
1313 next; # skip non-ordinary-files
1314 }
1315 unlink $dstname;
1316 copy($src, $dstname)
1317 or warn "Unable to copy $src to $dstname: $!";
1318 }
1319 }
1320
1321
1322 sub open_browser_on {
1323 my $index = shift;
1324
1325 my $exit_code = eval { require Browser::Open; Browser::Open::open_browser($index, 1); };
1326 return if defined($exit_code) && $exit_code == 0;
1327 warn "$@\n" if $@ && $opt_debug;
1328
1329 return if eval { require ActiveState::Browser; ActiveState::Browser::open($index); 1 };
1330 warn "$@\n" if $@ && $opt_debug && $^O eq "MSWin32";
1331
1332
1333 my $BROWSER;
1334 if ($^O eq "MSWin32") {
1335 $BROWSER = "start %s";
1336 }
1337 elsif ($^O eq "darwin") {
1338 $BROWSER = "/usr/bin/open %s";
1339 }
1340 else {
1341 my @try;
1342 if ($ENV{BROWSER}) {
1343 push(@try, split(/:/, $ENV{BROWSER}));
1344 }
1345 else {
1346 push(@try, qw(firefox galeon mozilla opera netscape));
1347 }
1348 unshift(@try, "kfmclient") if $ENV{KDE_FULL_SESSION};
1349 unshift(@try, "gnome-open") if $ENV{GNOME_DESKTOP_SESSION_ID};
1350 unshift(@try, "xdg-open");
1351 for (grep { have_prog($_) } @try) {
1352 if ($_ eq "kfmclient") {
1353 $BROWSER = "$_ openURL %s";
1354 }
1355 elsif ($_ eq "gnome-open" || $_ eq "opera") {
1356 $BROWSER = "$_ %s";
1357 }
1358 else {
1359 $BROWSER = "$_ %s &";
1360 }
1361 last;
1362 }
1363 }
1364 if ($BROWSER) {
1365 (my $cmd = $BROWSER) =~ s/%s/"$index"/;
1366 warn "Running $cmd\n" if $opt_debug;
1367 system($cmd);
1368 }
1369 else {
1370 warn "Don't know how to invoke your web browser.\nPlease visit $index yourself!\n";
1371 }
1372 }
1373
1374
1375 sub have_prog {
1376 my $prog = shift;
1377 for (split($Config{path_sep}, $ENV{PATH})) {
1378 return 1 if -x "$_/$prog";
1379 }
1380 return 0;
1381 }
1382
1383
1384 sub output_file_table {
1385 my ($fh, $profile, $add_totals) = @_;
1386
1387 # generate time-sorted sections for files
1388 print $fh qq{
1389 <table id="filestable" border="1" cellspacing="0" class="tablesorter floatHeaders">
1390 <caption>Source Code Files &mdash; ordered by exclusive time then name</caption>
1391 };
1392 print $fh qq{
1393 <thead><tr class="index">
1394 <th>Stmts</th><th>Exclusive<br />Time</th>
1395 <th>Reports</th><th>Source File</th>
1396 </tr></thead>
1397 <tbody>
1398 };
1399
1400 my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);
1401
1402 my $allTimes = $profile->{attribute}{total_stmts_duration};
1403 my $allCalls = $profile->{attribute}{total_stmts_measured}
1404 - $profile->{attribute}{total_stmts_discounted};
1405 # file in which sawampersand was noted during profiling
1406 my $sawampersand_fi = $profile->fileinfo_of($profile->{attribute}{sawampersand_fid}, 1);
1407
1408 my (@t_stmt_exec, @t_stmt_time);
1409 my @fis = $profile->noneval_fileinfos;
1410 @fis = sort { $b->meta->{'time'} <=> $a->meta->{'time'} } @fis;
1411
1412 my $dev_time = calculate_median_absolute_deviation([map { scalar $_->meta->{'time'} } @fis], 1);
1413
1414 foreach my $fi (@fis) {
1415 my $meta = $fi->meta;
1416 my $fid = $fi->fid;
1417 my @extra;
1418 my $css_class = 'index';
1419
1420 # The stats in this table include rolled up sums of nested evals.
1421
1422 my ($eval_stmts, $eval_time) = (0,0);
1423 if (my @has_evals = $fi->has_evals(1)) {
1424 my $n_evals = scalar @has_evals;
1425 my $msg = sprintf "including %d string eval%s", $n_evals, ($n_evals>1) ? "s" : "";
1426 if (my @nested = grep { $_->eval_fid != $fid } @has_evals) {
1427 $msg .= sprintf ": %d direct plus %d nested",
1428 $n_evals-@nested, scalar @nested;
1429 }
1430 push @extra, $msg;
1431 $eval_stmts = sum(map { $_->sum_of_stmts_count } @has_evals);
1432 $eval_time = sum(map { $_->sum_of_stmts_time } @has_evals);
1433 }
1434 # is this file one where we sawampersand (or contains an eval that is)?
1435 if ($sawampersand_fi
1436 && $] < 5.017008
1437 && $fi == ($sawampersand_fi->outer || $sawampersand_fi)
1438 ) {
1439 my $in_eval = ($fi == $sawampersand_fi)
1440 ? 'here'
1441 : sprintf q{<a %s>in eval here</a>}, $reporter->href_for_file($sawampersand_fi, undef, 'line');
1442 push @extra, sprintf qq{variables that impact regex performance for whole application seen $in_eval},
1443 $css_class = "warn $css_class";
1444 }
1445
1446 print $fh qq{<tr class="$css_class">};
1447
1448 my $stmts = $meta->{'calls'} + $eval_stmts;
1449 print $fh determine_severity($stmts, undef, 0,
1450 ($allCalls) ? sprintf("%.1f%%", $stmts/$allCalls*100) : ''
1451 );
1452 push @t_stmt_exec, $stmts;
1453
1454 my $time = $meta->{'time'} + $eval_time;
1455 print $fh determine_severity($time, $dev_time, 1,
1456 ($allTimes) ? sprintf("%.1f%%", $time/$allTimes*100) : ''
1457 );
1458 push @t_stmt_time, $time;
1459
1460
1461 my %levels = reverse %{$profile->get_profile_levels};
1462 my $rep_links = join '&nbsp;&bull;&nbsp;', map {
1463 sprintf(qq{<a %s>%s</a>}, $reporter->href_for_file($fi, undef, $_), $_)
1464 } grep { $levels{$_} } qw(line block sub);
1465 print $fh "<td>$rep_links</td>";
1466
1467 print $fh sprintf q{<td><a name="f%s" title="%s">%s</a> %s</td>},
1468 $fi->fid, $fi->abs_filename, $fi->filename_without_inc,
1469 (@extra) ? sprintf("(%s)", join "; ", @extra) : "";
1470 print $fh "</tr>\n";
1471 }
1472 print $fh "</tbody>\n";
1473
1474 if ($add_totals) {
1475 print $fh "<tfoot>\n";
1476 my $stats_fmt =
1477 qq{<tr class="index"><td class="n">%s</td><td class="n">%s</td><td colspan="2" style="font-style: italic">%s</td></tr>};
1478 my $t_notes = "";
1479 my $stmt_time_diff = $allTimes - sum(@t_stmt_time);
1480 if (sum(@t_stmt_exec) != $allCalls or $stmt_time_diff > 0.001) {
1481 $stmt_time_diff = ($stmt_time_diff > 0.001)
1482 ? sprintf(" and %s", fmt_time($stmt_time_diff)) : "";
1483 $t_notes = sprintf "(%d statements%s are unaccounted for)",
1484 $allCalls - sum(@t_stmt_exec), $stmt_time_diff;
1485 }
1486 print $fh sprintf $stats_fmt, fmt_float(sum(@t_stmt_exec)), fmt_time(sum(@t_stmt_time)),
1487 "Total $t_notes"
1488 if @t_stmt_exec > 1 or $t_notes;
1489
1490 if (@t_stmt_exec > 1) {
1491 print $fh sprintf $stats_fmt,
1492 int(fmt_float(sum(@t_stmt_exec) / @t_stmt_exec)),
1493 fmt_time( sum(@t_stmt_time) / @t_stmt_time), "Average";
1494 print $fh sprintf $stats_fmt, '', fmt_time( $dev_time->[1]), "Median";
1495 print $fh sprintf $stats_fmt, '', fmt_float($dev_time->[0]), "Deviation"
1496 if $dev_time->[0];
1497 }
1498
1499 print $fh "</tfoot>\n";
1500 }
1501
1502 print $fh '</table>';
1503 push @on_ready_js, q{
1504 $("#filestable").tablesorter({
1505 sortList: [[1,1],[3,1]],
1506 headers: {
1507 1: { sorter: 'fmt_time' },
1508 2: { sorter: false }
1509 }
1510 });
1511
1512 $(".floatHeaders").each( function(){ $(this).floatThead(); } );
1513
1514 show_fragment_target();
1515 $(window).on('hashchange', function(e){
1516 show_fragment_target();
1517 });
1518 };
1519
1520 return "";
1521 }
1522
1523 # calculates how good or bad the time is for a file based on the others
1524 sub determine_severity {
1525 my $val = shift;
1526 return "<td></td>" unless defined $val;
1527 my $stats = shift; # @_[3] is like arrayref (deviation, mean)
1528 my $is_time = shift;
1529 my $title = shift;
1530
1531 # normalize the width/precision so that the tables look good.
1532 my $fmt_val = ($is_time)
1533 ? fmt_time($val)
1534 : fmt_float($val, NUMERIC_PRECISION);
1535
1536 my $class;
1537 if (defined $stats) {
1538
1539 my $devs = ($val - $stats->[1]); #stats->[1] is the mean.
1540 $devs /= $stats->[0] if $stats->[0]; # no divide by zero when all values equal
1541
1542 if ($devs < 0) { # fast
1543 $class = 'c3';
1544 }
1545 elsif ($devs < SEVERITY_GOOD) {
1546 $class = 'c3';
1547 }
1548 elsif ($devs < SEVERITY_BAD) {
1549 $class = 'c2';
1550 }
1551 elsif ($devs < SEVERITY_SEVERE) {
1552 $class = 'c1';
1553 }
1554 else {
1555 $class = 'c0';
1556 }
1557 }
1558 else {
1559 $class = 'n';
1560 }
1561
1562 if ($title) {
1563 $title = (ref $title) ? $$title : _escape_html($title);
1564 $fmt_val = qq{<span title="$title">$fmt_val</span>};
1565 }
1566
1567 return qq{<td class="$class">$fmt_val</td>};
1568 }
1569
1570
1571 # return an html string with buttons for switching between profile levels of detail
1572 sub get_level_buttons {
1573 my $mode_ref = shift;
1574 my $file = shift;
1575 my $level = shift;
1576
1577 my $html = join '&emsp;&bull;&emsp;', map {
1578 my $mode = $mode_ref->{$_};
1579
1580 if ($mode eq $level) {
1581 qq{<span class="mode_btn mode_btn_selected">$mode view</span>};
1582 }
1583 else {
1584 my $mode_file = $file;
1585
1586 # replace the mode specifier in the output file name -- file-name-MODE.html
1587 $mode_file =~ s/(.*-).*?\.html/$1$mode.html/o;
1588
1589 qq{<span class="mode_btn"><a href="$mode_file">$mode view</a></span>};
1590 }
1591 } keys %$mode_ref;
1592
1593 return qq{<span>&laquo;&emsp;$html&emsp;&raquo;</span>};
1594 }
1595
1596
1597 sub get_footer {
1598 my ($profile) = @_;
1599 my $version = $Devel::NYTProf::Core::VERSION;
1600
1601 my $js = '';
1602 if (@on_ready_js) {
1603 # XXX I've no idea why this workaround is needed (or works).
1604 # without it the file table on the index page isn't sortable
1605 @on_ready_js = reverse @on_ready_js;
1606
1607 $js = sprintf q{
1608 <script type="text/javascript">
1609 $(document).ready(function() { %s } );
1610 </script>
1611 }, join("\n", '', @on_ready_js, '');
1612 @on_ready_js = ();
1613 };
1614
1615 # spacing so links to #line near can put right line at top near the bottom of the report
1616 my $spacing = "<br />" x 10;
1617 return qq{
1618 $js
1619 <div class="footer">Report produced by the
1620 <a href="http://metacpan.org/release/Devel-NYTProf/">NYTProf $version</a>
1621 Perl profiler, developed by
1622 <a href="http://www.linkedin.com/in/timbunce">Tim Bunce</a> based on
1623 work by Adam Kaplan and Salvador Fandiño García.
1624 </div>
1625 $spacing
1626 };
1627 }
1628
1629 # returns the generic header string. Here only to make the code more readable.
1630 sub get_html_header {
1631 my $title = shift || "Profile Index - NYTProf";
1632 my $opts = shift || {};
1633
1634 $title = _escape_html($title);
1635
1636 my $html = <<EOD;
1637 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1638 <html xmlns="http://www.w3.org/1999/xhtml">
1639 EOD
1640 $html = "<html>" if $opts->{not_xhtml};
1641 $html .= <<EOD;
1642 <!--
1643 This file was generated by Devel::NYTProf version $Devel::NYTProf::Core::VERSION
1644 -->
1645 <head>
1646 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1647 <meta http-equiv="Content-Language" content="en-us" />
1648 <meta name="robots" content="noindex,nofollow" />
1649 <title>$title</title>
1650 EOD
1651
1652 $html .= qq{ <link rel="stylesheet" type="text/css" href="style.css" />\n}
1653 unless $opts->{skip_style};
1654
1655 if (my $css = $opts->{add_jit}) {
1656 $html .= qq{ <link rel="stylesheet" type="text/css" href="js/jit/$css.css" />\n};
1657 $html .= qq{ <script language="JavaScript" src="js/jit/jit.js"></script>\n};
1658 }
1659
1660 $html .= <<'EOD' unless $opts->{skip_jquery};
1661 <script type="text/javascript" src="js/jquery-min.js"></script>
1662
1663 <script type="text/javascript" src="js/jquery.floatThead.min.js"></script>
1664 <script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
1665 <link rel="stylesheet" type="text/css" href="js/style-tablesorter.css" />
1666 <script type="text/javascript">
1667 // when a column is first clicked on to sort it, use descending order
1668 // XXX doesn't seem to work (and not just because the tablesorter formatSortingOrder() is broken)
1669 $.tablesorter.defaults.sortInitialOrder = "desc";
1670 // add parser through the tablesorter addParser method
1671 $.tablesorter.addParser({
1672 id: 'fmt_time', // name of this parser
1673 is: function(s) {
1674 return false; // return false so this parser is not auto detected
1675 },
1676 format: function(orig) { // format data for normalization
1677 // console.log(orig);
1678 var val = orig.replace(/ns/,'');
1679 if (val != orig) { return val / (1000*1000*1000); }
1680 val = orig.replace(/[µ\xB5]s/,''); /* micro */
1681 if (val != orig) { return val / (1000*1000); }
1682 val = orig.replace(/ms/,'');
1683 if (val != orig) { return val / (1000); }
1684 val = orig.replace(/([0-9])s/,"$1");
1685 if (val != orig) { return val; }
1686 if (orig == '0') { return orig; }
1687 var non_number = orig.replace(/^[-+]?[0-9.]+/, '', 'g');
1688 console.log('no match for fmt_time of '+orig+' (units:'+non_number+' charCodeAt0:'+non_number.charCodeAt(0)+')');
1689 return orig;
1690 },
1691 type: 'numeric' // set type, either numeric or text
1692 });
1693
1694 function show_fragment_target() {
1695 var tgt = $(':target');
1696 var table = tgt.closest('table.floatHeaders');
1697 if( tgt.is('a') && table.is('table.floatHeaders') )
1698 {
1699 var cury = $(window).scrollTop();
1700 var fhYPos = table.prev('.floatThead-container').offset().top;
1701 var thHeight = table.find('thead').first().height();
1702 var tYPos = parseInt($(':target').closest('tr').position().top);
1703 if( tYPos < (fhYPos + thHeight) )
1704 {
1705 $(window).scrollTop(
1706 tYPos - (thHeight)
1707 );
1708 }
1709 }
1710 }
1711 </script>
1712 EOD
1713 $html .= $opts->{head_epilogue} if $opts->{head_epilogue};
1714
1715 $html .= <<EOD;
1716 </head>
1717 EOD
1718
1719 return $html;
1720 }
1721
1722 sub get_page_header {
1723 my %args = @_;
1724 my ($profile, $head1, $head2, $right1, $right2, $skip_link_to_index) = (
1725 $args{profile}, $args{title}, $args{subtitle},
1726 $args{title2}, $args{subtitle2}, $args{skip_link_to_index}
1727 );
1728
1729 $head2 ||= qq{<br />For ${ \($profile->{attribute}{application}) }};
1730 $right1 ||= "&nbsp;";
1731 $right2 ||= "Run on ${ \scalar localtime($profile->{attribute}{basetime}) }<br />Reported on "
1732 . localtime(time);
1733
1734 my $back_link = q//;
1735 unless ($skip_link_to_index) {
1736 $back_link = qq{<div class="header_back">
1737 <a href="index.html">&larr; Index</a>
1738 </div>};
1739 }
1740
1741 my @body_attribs;
1742 push @body_attribs, qq{onload="$args{body_onload}"} if $args{body_onload};
1743 my $body_attribs = join "; ", @body_attribs;
1744
1745 return qq{<body $body_attribs>
1746 <div class="header" style="position: relative; overflow-x: hidden; overflow-y: hidden; z-index: 0; ">
1747 $back_link
1748 <div class="headerForeground" style="float: left">
1749 <span class="siteTitle">$head1</span>
1750 <span class="siteSubtitle">$head2</span>
1751 </div>
1752 <div class="headerForeground" style="float: right; text-align: right">
1753 <span class="siteTitle">$right1</span>
1754 <span class="siteSubtitle">$right2</span>
1755 </div>
1756 <div style="position: absolute; left: 0px; top: 0%; width: 100%; height: 101%; z-index: -1; background-color: rgb(17, 136, 255); "></div>
1757 <div style="position: absolute; left: 0px; top: 2%; width: 100%; height: 99%; z-index: -1; background-color: rgb(16, 134, 253); "></div>
1758 <div style="position: absolute; left: 0px; top: 4%; width: 100%; height: 97%; z-index: -1; background-color: rgb(16, 133, 252); "></div>
1759 <div style="position: absolute; left: 0px; top: 6%; width: 100%; height: 95%; z-index: -1; background-color: rgb(15, 131, 250); "></div>
1760 <div style="position: absolute; left: 0px; top: 8%; width: 100%; height: 93%; z-index: -1; background-color: rgb(15, 130, 249); "></div>
1761 <div style="position: absolute; left: 0px; top: 10%; width: 100%; height: 91%; z-index: -1; background-color: rgb(15, 129, 248); "></div>
1762 <div style="position: absolute; left: 0px; top: 12%; width: 100%; height: 89%; z-index: -1; background-color: rgb(14, 127, 246); "></div>
1763 <div style="position: absolute; left: 0px; top: 14%; width: 100%; height: 87%; z-index: -1; background-color: rgb(14, 126, 245); "></div>
1764 <div style="position: absolute; left: 0px; top: 16%; width: 100%; height: 85%; z-index: -1; background-color: rgb(14, 125, 244); "></div>
1765 <div style="position: absolute; left: 0px; top: 18%; width: 100%; height: 83%; z-index: -1; background-color: rgb(13, 123, 242); "></div>
1766 <div style="position: absolute; left: 0px; top: 20%; width: 100%; height: 81%; z-index: -1; background-color: rgb(13, 122, 241); "></div>
1767 <div style="position: absolute; left: 0px; top: 22%; width: 100%; height: 79%; z-index: -1; background-color: rgb(13, 121, 240); "></div>
1768 <div style="position: absolute; left: 0px; top: 24%; width: 100%; height: 77%; z-index: -1; background-color: rgb(12, 119, 238); "></div>
1769 <div style="position: absolute; left: 0px; top: 26%; width: 100%; height: 75%; z-index: -1; background-color: rgb(12, 118, 237); "></div>
1770 <div style="position: absolute; left: 0px; top: 28%; width: 100%; height: 73%; z-index: -1; background-color: rgb(12, 116, 235); "></div>
1771 <div style="position: absolute; left: 0px; top: 30%; width: 100%; height: 71%; z-index: -1; background-color: rgb(11, 115, 234); "></div>
1772 <div style="position: absolute; left: 0px; top: 32%; width: 100%; height: 69%; z-index: -1; background-color: rgb(11, 114, 233); "></div>
1773 <div style="position: absolute; left: 0px; top: 34%; width: 100%; height: 67%; z-index: -1; background-color: rgb(11, 112, 231); "></div>
1774 <div style="position: absolute; left: 0px; top: 36%; width: 100%; height: 65%; z-index: -1; background-color: rgb(10, 111, 230); "></div>
1775 <div style="position: absolute; left: 0px; top: 38%; width: 100%; height: 63%; z-index: -1; background-color: rgb(10, 110, 229); "></div>
1776 <div style="position: absolute; left: 0px; top: 40%; width: 100%; height: 61%; z-index: -1; background-color: rgb(10, 108, 227); "></div>
1777 <div style="position: absolute; left: 0px; top: 42%; width: 100%; height: 59%; z-index: -1; background-color: rgb(9, 107, 226); "></div>
1778 <div style="position: absolute; left: 0px; top: 44%; width: 100%; height: 57%; z-index: -1; background-color: rgb(9, 106, 225); "></div>
1779 <div style="position: absolute; left: 0px; top: 46%; width: 100%; height: 55%; z-index: -1; background-color: rgb(9, 104, 223); "></div>
1780 <div style="position: absolute; left: 0px; top: 48%; width: 100%; height: 53%; z-index: -1; background-color: rgb(8, 103, 222); "></div>
1781 <div style="position: absolute; left: 0px; top: 50%; width: 100%; height: 51%; z-index: -1; background-color: rgb(8, 102, 221); "></div>
1782 <div style="position: absolute; left: 0px; top: 52%; width: 100%; height: 49%; z-index: -1; background-color: rgb(8, 100, 219); "></div>
1783 <div style="position: absolute; left: 0px; top: 54%; width: 100%; height: 47%; z-index: -1; background-color: rgb(7, 99, 218); "></div>
1784 <div style="position: absolute; left: 0px; top: 56%; width: 100%; height: 45%; z-index: -1; background-color: rgb(7, 97, 216); "></div>
1785 <div style="position: absolute; left: 0px; top: 58%; width: 100%; height: 43%; z-index: -1; background-color: rgb(7, 96, 215); "></div>
1786 <div style="position: absolute; left: 0px; top: 60%; width: 100%; height: 41%; z-index: -1; background-color: rgb(6, 95, 214); "></div>
1787 <div style="position: absolute; left: 0px; top: 62%; width: 100%; height: 39%; z-index: -1; background-color: rgb(6, 93, 212); "></div>
1788 <div style="position: absolute; left: 0px; top: 64%; width: 100%; height: 37%; z-index: -1; background-color: rgb(6, 92, 211); "></div>
1789 <div style="position: absolute; left: 0px; top: 66%; width: 100%; height: 35%; z-index: -1; background-color: rgb(5, 91, 210); "></div>
1790 <div style="position: absolute; left: 0px; top: 68%; width: 100%; height: 33%; z-index: -1; background-color: rgb(5, 89, 208); "></div>
1791 <div style="position: absolute; left: 0px; top: 70%; width: 100%; height: 31%; z-index: -1; background-color: rgb(5, 88, 207); "></div>
1792 <div style="position: absolute; left: 0px; top: 72%; width: 100%; height: 29%; z-index: -1; background-color: rgb(4, 87, 206); "></div>
1793 <div style="position: absolute; left: 0px; top: 74%; width: 100%; height: 27%; z-index: -1; background-color: rgb(4, 85, 204); "></div>
1794 <div style="position: absolute; left: 0px; top: 76%; width: 100%; height: 25%; z-index: -1; background-color: rgb(4, 84, 203); "></div>
1795 <div style="position: absolute; left: 0px; top: 78%; width: 100%; height: 23%; z-index: -1; background-color: rgb(3, 82, 201); "></div>
1796 <div style="position: absolute; left: 0px; top: 80%; width: 100%; height: 21%; z-index: -1; background-color: rgb(3, 81, 200); "></div>
1797 <div style="position: absolute; left: 0px; top: 82%; width: 100%; height: 19%; z-index: -1; background-color: rgb(3, 80, 199); "></div>
1798 <div style="position: absolute; left: 0px; top: 84%; width: 100%; height: 17%; z-index: -1; background-color: rgb(2, 78, 197); "></div>
1799 <div style="position: absolute; left: 0px; top: 86%; width: 100%; height: 15%; z-index: -1; background-color: rgb(2, 77, 196); "></div>
1800 <div style="position: absolute; left: 0px; top: 88%; width: 100%; height: 13%; z-index: -1; background-color: rgb(2, 76, 195); "></div>
1801 <div style="position: absolute; left: 0px; top: 90%; width: 100%; height: 11%; z-index: -1; background-color: rgb(1, 74, 193); "></div>
1802 <div style="position: absolute; left: 0px; top: 92%; width: 100%; height: 9%; z-index: -1; background-color: rgb(1, 73, 192); "></div>
1803 <div style="position: absolute; left: 0px; top: 94%; width: 100%; height: 7%; z-index: -1; background-color: rgb(1, 72, 191); "></div>
1804 <div style="position: absolute; left: 0px; top: 96%; width: 100%; height: 5%; z-index: -1; background-color: rgb(0, 70, 189); "></div>
1805 <div style="position: absolute; left: 0px; top: 98%; width: 100%; height: 3%; z-index: -1; background-color: rgb(0, 69, 188); "></div>
1806 <div style="position: absolute; left: 0px; top: 100%; width: 100%; height: 1%; z-index: -1; background-color: rgb(0, 68, 187); "></div>
1807 </div>\n};
1808 }
1809
1810 sub get_css {
1811 return <<'EOD';
1812 /* Stylesheet for Devel::NYTProf::Reader HTML reports */
1813
1814 /* You may modify this file to alter the appearance of your coverage
1815 * reports. If you do, you should probably flag it read-only to prevent
1816 * future runs from overwriting it.
1817 */
1818
1819 /* Note: default values use the color-safe web palette. */
1820 a { color: blue; }
1821 a:visited { color: #6d00E6; }
1822 a:hover { color: red; }
1823
1824 body { font-family: sans-serif; margin: 0px; background-color: white; color:#222; }
1825 .body_content { margin: 8px; }
1826
1827 .header { font-family: sans-serif; padding-left: 0.5em; padding-right: 0.5em; }
1828 .headerForeground { color: white; padding: 10px; padding-top: 50px; }
1829 .siteTitle { font-size: 2em; }
1830 .siteSubTitle { font-size: 1.2em; }
1831
1832 .header_back {
1833 position: absolute;
1834 padding: 10px;
1835 }
1836 .header_back > a:link,
1837 .header_back > a:visited {
1838 color: white;
1839 text-decoration: none;
1840 font-size: 0.75em;
1841 }
1842
1843 .jump_to_file {
1844 margin-top: 20px;
1845 }
1846
1847 .footer,
1848 .footer > a:link,
1849 .footer > a:visited {
1850 color: #cccccc;
1851 }
1852 .footer { margin: 30px; }
1853
1854 table {
1855 border-collapse: collapse;
1856 border-spacing: 0px;
1857 margin-top: 20px;
1858 }
1859 tr {
1860 text-align : center;
1861 vertical-align: top;
1862 }
1863 th,.h {
1864 background-color: #dddddd;
1865 border: solid 1px #666666;
1866 padding: 0em 0.4em 0em 0.4em;
1867 font-size:0.8em;
1868 }
1869 td {
1870 border: solid 1px #cccccc;
1871 padding: 0em 0.4em 0em 0.4em;
1872 }
1873 caption {
1874 background-color: #dddddd;
1875 text-align: left;
1876 white-space: pre;
1877 padding: 0.4em;
1878 }
1879
1880 .table_footer { color: gray; }
1881 .table_footer > a:link,
1882 .table_footer > a:visited { color: gray; }
1883 .table_footer > a:hover { color: red; }
1884
1885 .index { text-align: left; }
1886
1887 .mode_btn_selected {
1888 font-style: italic;
1889 }
1890
1891 /* subroutine dispatch table */
1892 .sub_name {
1893 text-align: left;
1894 font-family: monospace;
1895 white-space: pre;
1896 color: gray;
1897 }
1898
1899 /* source code */
1900 th.left_indent_header {
1901 padding-left: 15px;
1902 text-align: left;
1903 }
1904
1905 pre,.s {
1906 text-align: left;
1907 font-family: monospace;
1908 white-space: pre;
1909 }
1910 /* plain number */
1911 .n { text-align: right }
1912
1913 /* Classes for color-coding profiling information:
1914 * c0 : code not hit
1915 * c1 : coverage >= 75%
1916 * c2 : coverage >= 90%
1917 * c3 : path covered or coverage = 100%
1918 */
1919 .c0, .c1, .c2, .c3 { text-align: right; }
1920 .c0 { background-color: #ffb3b3; } /* red */
1921 .c1 { background-color: #ffd9b4; } /* orange */
1922 .c2 { background-color: #ffffB4; } /* yellow */
1923 .c3 { background-color: #B4ffB4; } /* green */
1924
1925 /* warnings */
1926 .warn {
1927 background-color: #FFFFAA;
1928 border: 0;
1929 width: 96%;
1930 text-align: center;
1931 padding: 5px 0;
1932 }
1933 .warn_title {
1934 background-color: #FFFFAA;
1935 border: 0;
1936 color: red;
1937 width: 96%;
1938 font-size: 2em;
1939 text-align: center;
1940 padding: 5px 0;
1941 }
1942
1943 /* summary of calls into and out of a sub */
1944 .calls {
1945 display: block;
1946 color: gray;
1947 padding-top: 5px;
1948 padding-bottom: 5px;
1949 text-decoration: none;
1950 }
1951 .calls:hover {
1952 background-color: #e8e8e8;
1953 color: black;
1954 }
1955 .calls a { color: gray; text-decoration: none; }
1956 .calls:hover a { color: black; text-decoration: underline; }
1957 .calls:hover a:hover { color: red; }
1958 /* give a little headroom to the summary of calls into a sub */
1959 .calls .calls_in { margin-top: 5px; }
1960
1961 .vis_header {
1962 text-align:center;
1963 font-style: italic;
1964 padding-top: 5px; color: gray;
1965 }
1966
1967 .flamegraph {
1968 margin: 20px 0px;
1969 }
1970
1971 EOD
1972 }
1973
1974 __END__
1975
1976 =head1 DESCRIPTION
1977
1978 Devel::NYTProf is a powerful feature-rich Perl source code profiler.
1979 See L<Devel::NYTProf> for details.
1980
1981 C<nytprofhtml> generates a set of html reports from a single data file
1982 generated by L<Devel::NYTProf>. (If your process forks you'll probably have
1983 multiple files. See L<Devel::NYTProf> and L<nytprofmerge>.)
1984
1985 The reports include dynamic runtime analysis wherein each line and each file
1986 is analyzed based on the performance of the other lines and files. As a
1987 result, you can quickly find the slowest module and the slowest line in a
1988 module. Slowness is measured in three ways: total calls, total time, and
1989 average time per call.
1990
1991 Coloring is based on absolute deviations from the median.
1992 See L<http://en.wikipedia.org/wiki/Median_absolute_deviation> for more details.
1993
1994 That might sound complicated, but in reality you can just run the command and
1995 enjoy your report!
1996
1997 =head1 COMMAND-LINE OPTIONS
1998
1999 =over 4
2000
2001 =item -f, --file <filename>
2002
2003 Specifies the location of the file generated by L<Devel::NYTProf>.
2004 Default: ./nytprof.out
2005
2006 =item -o, --out <dir>
2007
2008 The directory in which to place the generated report files. Default: ./nytprof/
2009
2010 =item -d, --delete
2011
2012 Purge any existing contents of the report output directory.
2013
2014 =item -l, --lib <dir>
2015
2016 Add a path to the beginning of @INC to help nytprofhtml find the source files
2017 used by the code. Should not be needed in practice.
2018
2019 =item --open
2020
2021 Make your web browser visit the report after it has been generated.
2022
2023 If this doesn't work well for you, try installing the L<Browser::Open> module.
2024
2025 =item -m, --minimal
2026
2027 Don't generate graphviz .dot files or block/sub-level reports.
2028
2029 =item --no-flame
2030
2031 Disable generation of the flamegraph on the index page.
2032 Also disables calculation of distinct call stacks that are used to produce the
2033 flamegraph.
2034
2035 =item -h, --help
2036
2037 Print the help message.
2038
2039 =back
2040
2041 =head1 SAMPLE OUTPUT
2042
2043 You can see a complete report for a large application at
2044 L<http://timbunce.github.io/devel-nytprof/sample-report/nytprof-20160319/index.html>
2045
2046 The report was generated by profiling L<perlcritic> 1.121 checking its own source code
2047 using perl v5.18.2.
2048
2049 =head1 DIAGNOSTICS
2050
2051 =head2 "Unable to open '... (autosplit into ...)'"
2052
2053 The profiled application executed code in a module that used L<AutoLoader> to
2054 load the code from a separate .al file. NYTProf automatically recognises this
2055 situation and tries to determine the 'parent' module file so it can associate
2056 the profile data with it. In order to do that the parent module file must
2057 already be 'known' to NYTProf, typically by already having some code profiled.
2058
2059 You're only likely to see this warning if you're using the C<start> option to
2060 start profiling after compile-time. The effect is that times spent in
2061 autoloaded subs won't be associated with the parent module file and you won't
2062 get annotated reports for them.
2063
2064 You can avoid this by using the default C<start=begin> option, or by ensuring
2065 you execute some non-autoloaded code in the parent module, while the profiler is
2066 running, before an autoloaded sub is called.
2067
2068
2069 =head2 Background
2070
2071 Subroutine-level profilers:
2072
2073 Devel::DProf | 1995-10-31 | ILYAZ
2074 Devel::AutoProfiler | 2002-04-07 | GSLONDON
2075 Devel::Profiler | 2002-05-20 | SAMTREGAR
2076 Devel::Profile | 2003-04-13 | JAW
2077 Devel::DProfLB | 2006-05-11 | JAW
2078 Devel::WxProf | 2008-04-14 | MKUTTER
2079
2080 Statement-level profilers:
2081
2082 Devel::SmallProf | 1997-07-30 | ASHTED
2083 Devel::FastProf | 2005-09-20 | SALVA
2084 Devel::NYTProf | 2008-03-04 | AKAPLAN
2085 Devel::Profit | 2008-05-19 | LBROCARD
2086
2087 Devel::NYTProf is a (now distant) fork of Devel::FastProf, which was itself an
2088 evolution of Devel::SmallProf.
2089
2090 Adam Kaplan took Devel::FastProf and added html report generation (based on
2091 Devel::Cover) and a test suite - a tricky thing to do for a profiler.
2092 Meanwhile Tim Bunce had been extending Devel::FastProf to add novel
2093 per-sub and per-block timing, plus subroutine caller tracking.
2094
2095 When Devel::NYTProf was released Tim switched to working on Devel::NYTProf
2096 because the html report would be a good way to show the extra profile data, and
2097 the test suite made development much easier and safer.
2098
2099 Then he went a little crazy and added a slew of new features, in addition to
2100 per-sub and per-block timing and subroutine caller tracking. These included the
2101 'opcode interception' method of profiling, ultra-fast and robust inclusive
2102 subroutine timing, doubling performance, plus major changes to html reporting
2103 to display all the extra profile call and timing data in richly annotated and
2104 cross-linked reports.
2105
2106 Steve Peters came on board along the way with patches for portability and to
2107 keep NYTProf working with the latest development Perl versions.
2108
2109 Adam's work is sponsored by The New York Times Co. L<http://open.nytimes.com>.
2110 Tim's work was partly sponsored by Shopzilla. L<http://www.shopzilla.com>.
2111
2112 =head1 SEE ALSO
2113
2114 Mailing list and discussion at L<http://groups.google.com/group/develnytprof-dev>
2115
2116 Public Github Repository and hacking instructions at L<https://github.com/timbunce/devel-nytprof/>
2117
2118 L<Devel::NYTProf>,
2119 L<Devel::NYTProf::Reader>,
2120 L<nytprofcsv>
2121
2122 =head1 AUTHOR
2123
2124 B<Adam Kaplan>, C<< <akaplan at nytimes.com> >>.
2125 B<Tim Bunce>, L<http://blog.timbunce.org>.
2126 B<Steve Peters>, C<< <steve at fisharerojo.org> >>.
2127
2128 =head1 COPYRIGHT AND LICENSE
2129
2130 This program is free software; you can redistribute it and/or modify
2131 it under the same terms as Perl itself, either Perl version 5.8.8 or,
2132 at your option, any later version of Perl 5 you may have available.
2133
2134 =cut
2135
2136 # vim:ts=8:sw=4:expandtab