#!/usr/bin/env perl
##########################################################
## This script is part of the Devel::NYTProf distribution
##
## Copyright, contact and other information can be found
## at the bottom of this file, or by going to:
## http://search.cpan.org/~akaplan/Devel-NYTProf
##
##########################################################
# $Id: nytprofhtml 477 2008-09-30 12:25:18Z tim.bunce $
###########################################################
use warnings;
use strict;

use Carp;
use Getopt::Long;
use List::Util qw(sum max);
use File::Copy;

use Devel::NYTProf::Reader;
use Devel::NYTProf::Core;
use Devel::NYTProf::Util qw(
    fmt_float fmt_incl_excl_time
    calculate_median_absolute_deviation
    get_abs_paths_alternation_regex
    html_safe_filename
);

our $VERSION = 1.02;

# These control the limits for what the script will consider ok to severe times
# specified in standard deviations from the mean time
use constant SEVERITY_SEVERE => 2.0;    # above this deviation, a bottleneck
use constant SEVERITY_BAD    => 1.0;
use constant SEVERITY_GOOD   => 0.5;    # within this deviation, okay

use constant NUMERIC_PRECISION => 5;

my %opt = (
    file => 'nytprof.out',
    out  => 'nytprof',
);
GetOptions(\%opt, qw/file|f=s delete|d out|o=s lib|l=s help|h/) or exit 1;

if (defined($opt{help})) {
    &usage;
    exit 1;
}

# handle file selection option
if (!-r $opt{file}) {
    die "$0: Unable to access $opt{file}\n";
}

# handle handle output location
if (!-e $opt{out}) {

    # will be created
}
elsif (!-d $opt{out}) {
    die "$0: Specified output directory `$opt{out}' is a file. whoops!\n";
}
elsif (!-w $opt{out}) {
    die "$0: Unable to write to output directory `$opt{out}'\n";
}

# handle deleting old db's
if (defined($opt{'delete'})) {
    _delete();
}

# handle custom lib path
if (defined($opt{lib})) {
    if (-d $opt{lib}) {
        unshift(@INC, $opt{lib});
    }
    else {
        die "$0: Specified lib directory `$opt{lib}' does not exist.\n";
    }
}

print "Generating report...\n";
my $reporter = new Devel::NYTProf::Reader($opt{file});

# place to store this crap
$reporter->output_dir($opt{out});

# set formatting for html
$reporter->set_param(
    'header',
    sub {
        my ($profile, $filestr, $output_filestr, $level) = @_;

        my $profile_level_buttons =
            get_level_buttons($profile->get_profile_levels, $output_filestr, $level);

        my $subhead = qq{&emsp;&emsp;$profile_level_buttons<br />
            For ${ \($profile->{attribute}{application}) }
        };

        get_html_header("Profile: !~FILENAME~!")
            . get_header(
            profile  => $profile,
            title    => "Performance Profile",
            subtitle => $subhead,
            mode     => qq/-$level/
            )
            . qq{<div class="body_content">
<br />
<table><tr>
<td class='h' align='right'>File</td><td align=\"left\">!~FILENAME~!</td></tr>
<td class='h' align='right'>Statements Executed</td><td align=\"left\">!~TOTAL_CALLS~!
</td></tr>\n
<td class='h' align='right'>Total Time</td><td align=\"left\">!~TOTAL_TIME~!
seconds</td>\n</tr></table><br/>
};
    }
);

$reporter->set_param(
    'taintmsg',
    "<div class='warn_title'>WARNING!</div>\n
<div class='warn'>The source file used to generate this report was modified
after the profiler database was generated. The database might be out of sync, you should regenerate it.  This page might not make any sense!</div><br/>\n"
);


sub calc_mad_from_objects {
    my ($ary, $meth, $ignore_zeros) = @_;
    return calculate_median_absolute_deviation([map { scalar $_->$meth } @$ary], $ignore_zeros,);
}

sub calc_mad_from_hashes {
    my ($ary, $meth, $ignore_zeros) = @_;
    return calculate_median_absolute_deviation([map { scalar $_->{$meth} } @$ary], $ignore_zeros,
    );
}

sub subroutine_table {
    my ($profile, $filestr, $max_subs, $sortby) = @_;
    $sortby ||= 'excl_time';

    my $subs_in_file = $profile->subs_defined_in_file($filestr, 0);
    return "" unless $subs_in_file && %$subs_in_file;

    my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);

    # XXX slow - use Schwartzian transform or via XS or Sort::Key
    my @subs =
        sort { $b->$sortby <=> $a->$sortby or $a->subname cmp $b->subname }
        values %$subs_in_file;

    my $dev_incl_time  = calc_mad_from_objects(\@subs, 'incl_time',    1);
    my $dev_excl_time  = calc_mad_from_objects(\@subs, 'excl_time',    1);
    my $dev_calls      = calc_mad_from_objects(\@subs, 'calls',        1);
    my $dev_call_count = calc_mad_from_objects(\@subs, 'caller_count', 1);
    my $dev_call_fids  = calc_mad_from_objects(\@subs, 'caller_fids',  1);

    my @subs_to_show = ($max_subs) ? splice @subs, 0, $max_subs : @subs;
    my $qualifier = (@subs > @subs_to_show) ? "Top $max_subs " : "";

    my $sub_links;

    my $sortby_desc = ($sortby eq 'excl_time') ? "exclusive time" : "inclusive time";
    $sub_links .= qq{<table border=1 cellpadding=0>
        <caption>${qualifier}Subroutines &mdash; ordered by $sortby_desc</caption>
        <tr>
        <th>Calls</th>
        <th><span title="Number of Places sub is called from">P</span></th>
        <th><span title="Number of Files sub is called from">F</span></th>
        <th>Inclusive<br />Time</th>
        <th>Exclusive<br />Time</th>
        <th colspan=2 class="left_indent_header">Subroutine</th>
        </tr>
    };

    my @rows;
    for my $sub (@subs_to_show) {
        $sub_links .= "<tr>";

        $sub_links .= determine_severity(undef, $sub->calls        || 0, $dev_calls);
        $sub_links .= determine_severity(undef, $sub->caller_count || 0, $dev_call_count);
        $sub_links .= determine_severity(undef, $sub->caller_fids  || 0, $dev_call_fids);
        $sub_links .= determine_severity(undef, $sub->incl_time    || 0, $dev_incl_time);
        $sub_links .= determine_severity(undef, $sub->excl_time    || 0, $dev_excl_time);

        # package and subname
        my $subname = $sub->subname;

        # remove own filename from eg __ANON__[(eval 3)[/long/path/name.pm:99]:53]
        # XXX doesn't work right because $filestr isn't full filename
        $subname =~ s/\Q$filestr\E:(\d+)/:$1/g;
        my ($pkg, $subr) = ($subname =~ /^(.*::)(.*?)$/) ? ($1, $2) : ('', $subname);
        $sub_links .= sprintf qq{<td class="sub_pkg">%s</td>}, $pkg;

        $subr =~ s/$inc_path_regex//;    # for __ANON__[/very/long/path...]
        my $first_line = $sub->first_line;
        my $fileinfo   = $sub->fileinfo;
        if ($fileinfo and my ($outer_fileinfo, $outer_line) = $fileinfo->outer) {    # eval
            $fileinfo   = $outer_fileinfo;
            $first_line = $outer_line;
        }

        if ($sub->is_xsub) {
            $sub_links .= sprintf(qq{<td class="sub_sub">%s (xsub)</td>}, $subr);
        }
        else {
            $sub_links .= sprintf(
                qq{<td class="sub_sub"><a href="%s-line.html#%s">%s</a></td>},
                $fileinfo ? html_safe_filename($fileinfo->filename_without_inc) : "",
                $first_line || 'UNKNOWN', $subr
            );
        }

        $sub_links .= "<tr>\n";
    }
    $sub_links .= "</table>\n";

    return $sub_links;
}

$reporter->set_param(
    'datastart',
    sub {
        my ($profile, $filestr) = @_;

        my $sub_links = subroutine_table($profile, $filestr, undef, undef);

        return qq{$sub_links<br>
      <table border=1 cellpadding=0>
      <tr><th>Line</th><th>Stmts.</th><th>Exclusive<br />Time</th><th>Avg.</th><th class="left_indent_header">Code</th>
      </tr>\n
    };
    }
);

$reporter->set_param(
    'footer',
    sub {
        my ($profile, $filestr) = @_;
        my $footer = get_footer($profile);
        return "</table></div>$footer</body></html>";
    }
);

$reporter->set_param(
    'linestart',
    {   func => sub {
            my ($value, $linenum, $linesrc) = @_;
            sprintf qq{<tr><td class="h"><a name="%d"></a>%d</td>}, $linenum, $linenum;
        },
    }
);

$reporter->set_param(
    'column4',
    {   func => sub {
            my ($value, $linenum, $linesrc, $profile, $subs, $calls) = @_;

            $linesrc =~ s/&/&amp;/g;
            $linesrc =~ s/</&lt;/g;
            $linesrc =~ s/>/&gt;/g;
            $linesrc =~ s/\t/        /g;

            my @prologue;

            # for each of the subs defined on this line, who called them
            for my $sub_info (@$subs) {
                my $callers = $sub_info->callers;
                next unless $callers && %$callers;

                my @callers;
                while (my ($fid, $fid_line_info) = each %$callers) {
                    push @callers, [$fid, $_, @{$fid_line_info->{$_}}] for keys %$fid_line_info;
                }
                my $total_calls = sum(my @caller_calls = map { $_->[2] } @callers);
                my $max_calls = max(@caller_calls);
                my $avg_per_call = fmt_float($sub_info->incl_time / $total_calls);

                push @prologue, sprintf "# spent %s within %s which was called%s:",
                    fmt_incl_excl_time($sub_info->incl_time, $sub_info->excl_time),
                    $sub_info->subname, ($total_calls <= 1)
                    ? ""
                    : " $total_calls times, avg ${avg_per_call}s/call";

                # order by most frequent caller first
                @callers = sort { $b->[2] <=> $a->[2] } @callers;
                for my $caller (@callers) {
                    my ($fid, $line, $count, $incl_time, $excl_time) = @$caller;

                    my @subnames = $profile->subname_at_file_line($fid, $line);
                    my $subname = (@subnames) ? " by " . join(" or ", @subnames) : "";
                    my $avg_time =
                        ($count <= 1)
                        ? ""
                        : sprintf ", avg %ss/call", fmt_float($incl_time / $count);
                    my $times = sprintf " (%s+%ss)", fmt_float($excl_time),
                        fmt_float($incl_time - $excl_time);

                    my $filename = $profile->fid_filename($fid);
                    my $href = $reporter->get_file_stats()->{$filename}{html_safe} || "unknown";
                    my $caller_filename = $profile->fid_filename($fid);

                    push @prologue,
                        sprintf q{# %*s times%s%s at <a href="%s#%d">line %d</a> of %s%s},
                        length($max_calls), $count, $times, $subname, "$href.html", $line, $line,
                        $caller_filename, $avg_time;
                }
            }
            my $prologue = '';
            $prologue = sprintf qq{<div class="calls">%s</div>}, join("\n", @prologue)
                if @prologue;

            # give details of each of the subs called by this line
            my $epilogue = '';
            if (%$calls) {
                my @calls_to = sort {
                    $calls->{$b}[1] <=> $calls->{$a}[1] or    # incl_time
                        $a cmp $b
                } keys %$calls;
                my $max_calls_to = max(map { $_->[0] } values %$calls);
                my $ws = ($linesrc =~ m/^((?:&nbsp;|\s)+)/) ? $1 : '';
                $epilogue = join "\n", map {
                    my ($count, $incl_time) = @{$calls->{$_}};
                    my $href = $reporter->href_for_sub($_);
                    my $html = sprintf qq{%s# spent %ss making %*d calls to }, $ws,
                        fmt_float($incl_time), length($max_calls_to), $count;
                    $html .= ($href) ? sprintf(qq{<a href="%s">%s</a>}, $href, $_) : $_;
                    $html .= sprintf qq{, avg %ss/call}, fmt_float($incl_time / $count)
                        if $count > 1;
                    $html;
                } @calls_to;
                $epilogue = sprintf qq{<div class="calls">%s</div>}, $epilogue;
            }

            sprintf qq{<td class="s">%s%s%s</td>}, $prologue, $linesrc, $epilogue;
        },
    }
);


$reporter->set_param('column1', {value => 'calls',     func => \&determine_severity});
$reporter->set_param('column2', {value => 'time',      func => \&determine_severity});
$reporter->set_param('column3', {value => 'time/call', func => \&determine_severity});

$reporter->set_param('lineend', {start => "</tr>\n"});

# set output options
$reporter->set_param('suffix', '.html');

# output a css file too (optional, but good for pretty pages)
$reporter->_output_additional('style.css', [<DATA>]);

# generate the files
$reporter->report();

output_subs_indexpage($reporter, "index-subs-excl.html", 'excl_time');
output_subs_indexpage($reporter, "index-subs-incl.html", 'incl_time');
output_indexpage($reporter, "index.html");

output_js_files($reporter);


#
# SUBROUTINES
#

# output an html indexing page or subroutines
sub output_subs_indexpage {
    my ($r, $filename, $sortby) = @_;
    my $profile = $reporter->{profile};

    open(OUT, '>', "$opt{out}/$filename")
        or croak "Unable to open file $opt{out}/$filename: $!";

    print OUT get_html_header();
    print OUT get_header(profile => $profile, title => "Performance Profile Subroutine Index");
    print OUT qq{<div class="body_content"><br/>};

    # Show top subs across all files
    print OUT subroutine_table($profile, 0, 0, $sortby);

    my $footer = get_footer($profile);
    print OUT "</div>$footer</body></html>";
    close OUT;
}


# output an html indexing page with some information to help navigate potential
# large numbers of profiled files. Optional, recommended
sub output_indexpage {
    my ($r, $filename) = @_;
    my $profile = $reporter->{profile};
    my $stats   = $r->get_file_stats();

    ###
    open(OUT, '>', "$opt{out}/$filename")
        or croak "Unable to open file $opt{out}/$filename: $!";

    print OUT get_html_header();
    print OUT get_header(profile => $profile, title => "Performance Profile Index");
    print OUT qq{
        <div class="body_content"><br/>
    };

    # generate name-sorted select options for files, if there are many
    if (keys %$stats > 30) {
        print OUT
            qq{<form name="jump"><select name="file" onChange="location.href=document.jump.file.value;">\n};
        printf OUT qq{<option disabled>%s</option>\n}, "Jump to file...";
        foreach (sort keys %$stats) {
            my $fid = $profile->resolve_fid($_) or warn "Can't find fid for $_";
            printf OUT qq{<option value="#f%s">%s</option>\n}, $fid, $_;
        }
        print OUT "</select><form><br/>\n";
    }

    # Show top subs across all files
    my $max_subs = 15; # keep it less than a page so users can see the file table
    my $all_subs = keys %{$profile->{sub_subinfo}};
    print OUT subroutine_table($profile, 0, $max_subs, undef);
    if ($all_subs > $max_subs) {
        print OUT sprintf qq{<div class="table_footer">
            For more information see all %d subroutines
            <a href="%s">sorted by exclusive time</a>,
            or <a href="%s">sorted by inclusive time</a>.
            </div>
        }, $all_subs, "index-subs-excl.html", "index-subs-incl.html";
    }

    print OUT file_table($profile, $stats, 1);

    my $footer = get_footer($profile);
    print OUT "</div>$footer</body></html>";
    close OUT;
}


sub output_js_files {
    my ($profile) = @_;
    # find the js files installed with Devel::NYTProf
    (my $lib = $INC{"Devel/NYTProf/Data.pm"}) =~ s/Data\.pm$//;
    for my $src (<$lib/js/*.js>) {
        (my $file = $src) =~ s/.*\///;
        copy($src, "$opt{out}/$file")
            or warn "Unable to copy $src to $opt{out}/$file: $!";
    }
}


sub file_table {
    my ($profile, $stats, $add_totals) = @_;

    for (values %$stats) {
        next if not $_;
        $_->{'time/call'} = ($_->{calls}) ? $_->{'time'} / $_->{calls} : 0;
    }

    my $dev_time = calc_mad_from_hashes([values %$stats], 'time',      0);
    my $dev_avgt = calc_mad_from_hashes([values %$stats], 'time/call', 0);

    # generate time-sorted sections for files
    print OUT qq{
        <table border=1 cellspacing=0>
        <caption>Source Code Files &mdash; ordered by exclusive time then name</caption>
    };
    print OUT "<tr class='index'><th>Stmts</th><th>Exclusive<br />Time</th>"
        . "<th>Avg.</th><th>Reports</th><th>Source File</th></tr>";

    my $inc_path_regex = get_abs_paths_alternation_regex([$profile->inc], qr/^|\[/);

    my $allTimes = 0;    # for stats table at the bottom only
    my $allCalls = 0;    # for stats table at the bottom only

    foreach my $filestats (sort { $b->{'time'} <=> $a->{'time'} } values %$stats) {
        print OUT qq{<tr class="index">};
        print OUT "<td class='n'>$filestats->{calls}</td>";
        print OUT determine_severity('time',      $filestats->{'time'},      $dev_time);
        print OUT determine_severity('time/call', $filestats->{'time/call'}, $dev_avgt);

        my $rep_links = join '&nbsp;&bull;&nbsp;', map {
            my $level_html_safe = $filestats->{$_}->{html_safe};
            ($level_html_safe)
                ? sprintf(qq{<a href="%s.html">%s</a>}, $level_html_safe, $_)
                : ()
        } qw(line block sub);
        print OUT "<td>$rep_links</td>";

        my $filename = $filestats->{filename};
        my $fid = $profile->resolve_fid($filename) or warn "Can't find fid for $_";
        (my $shortname = $filename) =~ s/$inc_path_regex//;
        print OUT sprintf q{<td><a name="f%s" title="%s">%s</a></td>}, $fid, $filename,
            $shortname;
        print OUT "</tr>\n";

        # stats collection
        $allTimes += $filestats->{'time'};
        $allCalls += $filestats->{calls};
    }
    if ($add_totals) {
        my $stats_fmt =
            qq{<tr class="index"><td class="n">%s</td><td class="n">%s</td><td class="n">%s</td><td style="font-style: italic">%s</td></tr>};
        print OUT sprintf $stats_fmt, fmt_float($allCalls), fmt_float($allTimes), '', "Total";
        print OUT sprintf $stats_fmt, int(fmt_float($allCalls / keys %$stats)),
            fmt_float($allTimes / keys %$stats), '', "Average"
            if %$stats;    # avoid divide by zero
        print OUT sprintf $stats_fmt, '', fmt_float($dev_time->[1]), fmt_float($dev_avgt->[1]),
            "Median";
        print OUT sprintf $stats_fmt, '', fmt_float($dev_time->[0]), fmt_float($dev_avgt->[0]),
            "Deviation";
    }
    print OUT '</table>';

    return "";
}

# calculates how good or bad the time is for a file based on the others
sub determine_severity {
    my (undef, $val, $stats) = @_;    # @_[3] is like arrayref (deviation, mean)
    return "<td></td>" unless defined $val;

    # normalize the width/precision so that the tables look good.
    $val = fmt_float($val, NUMERIC_PRECISION);
    return qq{<td class="n">$val</td>} unless defined $stats;

    my $devs = ($val - $stats->[1]);    #stats->[1] is the mean.
    $devs /= $stats->[0] if $stats->[0];    # no divide by zero when all values equal

    my $class;
    if ($devs < 0) {                        # fast
        $class = 'c3';
    }
    elsif ($devs < SEVERITY_GOOD) {
        $class = 'c3';
    }
    elsif ($devs < SEVERITY_BAD) {
        $class = 'c2';
    }
    elsif ($devs < SEVERITY_SEVERE) {
        $class = 'c1';
    }
    else {
        $class = 'c0';
    }
    return "<td class='$class'>$val</td>";
}

# Delete the previous database/directory if it exists
sub _delete {
    if (-d $opt{out}) {
        print "Deleting $opt{out}\n";
        unlink glob($opt{out} . "/*");
        unlink glob($opt{out} . "/.*");
        rmdir $opt{out} or confess "Delete of $opt{out} failed: $!\n";
    }
}

sub usage {
    print <<END
usage: [perl] nytprofhtml [opts]
 --file <file>, -f <file>  Use the specified file as Devel::NYTProf database
                            file. [default: ./nytprof.out]
 --out <dir>,   -o <dir>   Place generated files here [default: ./nytprof]
 --delete,      -d         Delete the old nytprofhtml output [uses --out]
 --lib,         -l         Add a path to the beginning of \@INC
 --help,        -h         Print this message

This script of part of the Devel::NYTProf distribution.
See http://search.cpan.org/dist/Devel-NYTProf/ for details and copyright.
END
}


# return an html string with buttons for switching between profile levels of detail
sub get_level_buttons {
    my $mode_ref = shift;
    my $file     = shift;
    my $level    = shift;

    my $html = join '&emsp;&bull;&emsp;', map {
        my $mode = $mode_ref->{$_};

        if ($mode eq $level) {
            qq{<span class="mode_btn mode_btn_selected">$mode view</span>};
        }
        else {
            my $mode_file = $file;

            # replace the mode specifier in the output file name -- file-name-MODE.html
            $mode_file =~ s/(.*-).*?\.html/$1$mode.html/o;

            qq{<span class="mode_btn"><a href="$mode_file">$mode view</a></span>};
        }
    } keys %$mode_ref;

    return qq{<span>&laquo;&emsp;$html&emsp;&raquo;</span>};
}


sub get_footer {
    my ($profile) = @_;
    my $version = $Devel::NYTProf::Core::VERSION;

    # spacing so links to #line near can put right line at top near the bottom of the report
    my $spacing = "<br />" x 10;
    return qq{
        <br />
        <div class="footer">Report produced by the
        <a href="http://search.cpan.org/dist/Devel-NYTProf/">NYTProf $version</a>
        Perl profiler, developed by
        <a href="http://www.linkedin.com/in/timbunce">Tim Bunce</a> and
        <a href="http://code.nytimes.com">Adam Kaplan</a>.
        </div>
        $spacing
    };
}

# returns the generic header string.  Here only to make the code more readable.
sub get_html_header {
    my $title = shift || "Profile Index";
    return <<EOD
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
This file was generated by Devel::NYTProf::Reader HTML Version $VERSION
using Devel::NYTProf Version $Devel::NYTProf::Core::VERSION
These modules are free. They are licensed under the same terms as Perl itself.
-->
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
    <meta http-equiv="Content-Language" content="en-us"></meta>
    <link rel="stylesheet" type="text/css" href="style.css"></link>
    <title>$title</title>
</head>
EOD
}

sub get_header {
    my %args = @_;
    my ($profile, $head1, $head2, $right1, $right2, $mode) = (
        $args{profile}, $args{title},     $args{subtitle},
        $args{title2},  $args{subtitle2}, $args{mode}
    );

    $head2  ||= qq{<br />For ${ \($profile->{attribute}{application}) }};
    $right1 ||= "&nbsp;";
    $right2 ||= "Run on ${ \scalar localtime($profile->{attribute}{basetime}) }<br />Reported on "
        . localtime(time);

    my $back_link = q//;
    if ($mode) {
        $back_link = qq{<div class="header_back">
            <a href="index.html">&larr; Index</a>
        </div>};
    }

    return qq{<body> 
<div class="header" style="position: relative; overflow-x: hidden; overflow-y: hidden; z-index: 0; ">
$back_link
<div class="headerForeground" style="float: left">
    <span class="siteTitle">$head1</span>
    <span class="siteSubtitle">$head2<span>
</div>
<div class="headerForeground" style="float: right; text-align: right">
    <span class="siteTitle">$right1</span>
    <span class="siteSubtitle">$right2</span>
</div>
<div style="position: absolute; left: 0px; top: 0%; width: 100%; height: 101%; z-index: -1; background-color: rgb(17, 136, 255); "></div>
<div style="position: absolute; left: 0px; top: 2%; width: 100%; height: 99%; z-index: -1; background-color: rgb(16, 134, 253); "></div>
<div style="position: absolute; left: 0px; top: 4%; width: 100%; height: 97%; z-index: -1; background-color: rgb(16, 133, 252); "></div>
<div style="position: absolute; left: 0px; top: 6%; width: 100%; height: 95%; z-index: -1; background-color: rgb(15, 131, 250); "></div>
<div style="position: absolute; left: 0px; top: 8%; width: 100%; height: 93%; z-index: -1; background-color: rgb(15, 130, 249); "></div>
<div style="position: absolute; left: 0px; top: 10%; width: 100%; height: 91%; z-index: -1; background-color: rgb(15, 129, 248); "></div>
<div style="position: absolute; left: 0px; top: 12%; width: 100%; height: 89%; z-index: -1; background-color: rgb(14, 127, 246); "></div>
<div style="position: absolute; left: 0px; top: 14%; width: 100%; height: 87%; z-index: -1; background-color: rgb(14, 126, 245); "></div>
<div style="position: absolute; left: 0px; top: 16%; width: 100%; height: 85%; z-index: -1; background-color: rgb(14, 125, 244); "></div>
<div style="position: absolute; left: 0px; top: 18%; width: 100%; height: 83%; z-index: -1; background-color: rgb(13, 123, 242); "></div>
<div style="position: absolute; left: 0px; top: 20%; width: 100%; height: 81%; z-index: -1; background-color: rgb(13, 122, 241); "></div>
<div style="position: absolute; left: 0px; top: 22%; width: 100%; height: 79%; z-index: -1; background-color: rgb(13, 121, 240); "></div>
<div style="position: absolute; left: 0px; top: 24%; width: 100%; height: 77%; z-index: -1; background-color: rgb(12, 119, 238); "></div>
<div style="position: absolute; left: 0px; top: 26%; width: 100%; height: 75%; z-index: -1; background-color: rgb(12, 118, 237); "></div>
<div style="position: absolute; left: 0px; top: 28%; width: 100%; height: 73%; z-index: -1; background-color: rgb(12, 116, 235); "></div>
<div style="position: absolute; left: 0px; top: 30%; width: 100%; height: 71%; z-index: -1; background-color: rgb(11, 115, 234); "></div>
<div style="position: absolute; left: 0px; top: 32%; width: 100%; height: 69%; z-index: -1; background-color: rgb(11, 114, 233); "></div>
<div style="position: absolute; left: 0px; top: 34%; width: 100%; height: 67%; z-index: -1; background-color: rgb(11, 112, 231); "></div>
<div style="position: absolute; left: 0px; top: 36%; width: 100%; height: 65%; z-index: -1; background-color: rgb(10, 111, 230); "></div>
<div style="position: absolute; left: 0px; top: 38%; width: 100%; height: 63%; z-index: -1; background-color: rgb(10, 110, 229); "></div>
<div style="position: absolute; left: 0px; top: 40%; width: 100%; height: 61%; z-index: -1; background-color: rgb(10, 108, 227); "></div>
<div style="position: absolute; left: 0px; top: 42%; width: 100%; height: 59%; z-index: -1; background-color: rgb(9, 107, 226); "></div>
<div style="position: absolute; left: 0px; top: 44%; width: 100%; height: 57%; z-index: -1; background-color: rgb(9, 106, 225); "></div>
<div style="position: absolute; left: 0px; top: 46%; width: 100%; height: 55%; z-index: -1; background-color: rgb(9, 104, 223); "></div>
<div style="position: absolute; left: 0px; top: 48%; width: 100%; height: 53%; z-index: -1; background-color: rgb(8, 103, 222); "></div>
<div style="position: absolute; left: 0px; top: 50%; width: 100%; height: 51%; z-index: -1; background-color: rgb(8, 102, 221); "></div>
<div style="position: absolute; left: 0px; top: 52%; width: 100%; height: 49%; z-index: -1; background-color: rgb(8, 100, 219); "></div>
<div style="position: absolute; left: 0px; top: 54%; width: 100%; height: 47%; z-index: -1; background-color: rgb(7, 99, 218); "></div>
<div style="position: absolute; left: 0px; top: 56%; width: 100%; height: 45%; z-index: -1; background-color: rgb(7, 97, 216); "></div>
<div style="position: absolute; left: 0px; top: 58%; width: 100%; height: 43%; z-index: -1; background-color: rgb(7, 96, 215); "></div>
<div style="position: absolute; left: 0px; top: 60%; width: 100%; height: 41%; z-index: -1; background-color: rgb(6, 95, 214); "></div>
<div style="position: absolute; left: 0px; top: 62%; width: 100%; height: 39%; z-index: -1; background-color: rgb(6, 93, 212); "></div>
<div style="position: absolute; left: 0px; top: 64%; width: 100%; height: 37%; z-index: -1; background-color: rgb(6, 92, 211); "></div>
<div style="position: absolute; left: 0px; top: 66%; width: 100%; height: 35%; z-index: -1; background-color: rgb(5, 91, 210); "></div>
<div style="position: absolute; left: 0px; top: 68%; width: 100%; height: 33%; z-index: -1; background-color: rgb(5, 89, 208); "></div>
<div style="position: absolute; left: 0px; top: 70%; width: 100%; height: 31%; z-index: -1; background-color: rgb(5, 88, 207); "></div>
<div style="position: absolute; left: 0px; top: 72%; width: 100%; height: 29%; z-index: -1; background-color: rgb(4, 87, 206); "></div>
<div style="position: absolute; left: 0px; top: 74%; width: 100%; height: 27%; z-index: -1; background-color: rgb(4, 85, 204); "></div>
<div style="position: absolute; left: 0px; top: 76%; width: 100%; height: 25%; z-index: -1; background-color: rgb(4, 84, 203); "></div>
<div style="position: absolute; left: 0px; top: 78%; width: 100%; height: 23%; z-index: -1; background-color: rgb(3, 82, 201); "></div>
<div style="position: absolute; left: 0px; top: 80%; width: 100%; height: 21%; z-index: -1; background-color: rgb(3, 81, 200); "></div>
<div style="position: absolute; left: 0px; top: 82%; width: 100%; height: 19%; z-index: -1; background-color: rgb(3, 80, 199); "></div>
<div style="position: absolute; left: 0px; top: 84%; width: 100%; height: 17%; z-index: -1; background-color: rgb(2, 78, 197); "></div>
<div style="position: absolute; left: 0px; top: 86%; width: 100%; height: 15%; z-index: -1; background-color: rgb(2, 77, 196); "></div>
<div style="position: absolute; left: 0px; top: 88%; width: 100%; height: 13%; z-index: -1; background-color: rgb(2, 76, 195); "></div>
<div style="position: absolute; left: 0px; top: 90%; width: 100%; height: 11%; z-index: -1; background-color: rgb(1, 74, 193); "></div>
<div style="position: absolute; left: 0px; top: 92%; width: 100%; height: 9%; z-index: -1; background-color: rgb(1, 73, 192); "></div>
<div style="position: absolute; left: 0px; top: 94%; width: 100%; height: 7%; z-index: -1; background-color: rgb(1, 72, 191); "></div>
<div style="position: absolute; left: 0px; top: 96%; width: 100%; height: 5%; z-index: -1; background-color: rgb(0, 70, 189); "></div>
<div style="position: absolute; left: 0px; top: 98%; width: 100%; height: 3%; z-index: -1; background-color: rgb(0, 69, 188); "></div>
<div style="position: absolute; left: 0px; top: 100%; width: 100%; height: 1%; z-index: -1; background-color: rgb(0, 68, 187); "></div>
</div>\n};
}

# The data handle contains the entire CSS file.
__DATA__
/* Stylesheet for Devel::NYTProf::Reader HTML reports */

/* You may modify this file to alter the appearance of your coverage
 * reports. If you do, you should probably flag it read-only to prevent
 * future runs from overwriting it.
 */

/* Note: default values use the color-safe web palette. */
a:visited { color: #6d00E6; }
a:hover { color: red; }

body { font-family: sans-serif; margin: 0px; }
.body_content { margin: 8px; }

.header { font-family: sans-serif; padding-left: 1em; }
.headerForeground { color: white; padding: 10px; padding-top: 50px; }
.siteTitle { font-size: 2em; }
.siteSubTitle { font-size: 1.2em; }

.header_back { 
    position: absolute; 
    padding: 10px;
}
.header_back > a:link,
.header_back > a:visited {
    color: white; 
    text-decoration: none;
    font-size: 0.75em;
}

.footer,
.footer > a:link,
.footer > a:visited {
    color: #cccccc;
    text-decoration: none;
}
.footer { margin: 8px; }

table { 
    border-collapse: collapse; 
    border-spacing: 0px; 
    margin-top: 20px;
    margin-botom: 20px;
}
tr { 
    text-align : center;
    vertical-align: top; 
}
th,.h {
    background-color: #dddddd;
    border: solid 1px #666666;
    padding: 0em 0.4em 0em 0.4em;
}
td { 
    border: solid 1px #cccccc; 
    padding: 0em 0.4em 0em 0.4em;
}
caption {
    background-color: #dddddd;
    text-align: left;
    text-wrap: none;
    white-space: pre;
    padding: 0.4em;
}

.table_footer { color: grey; }
.table_footer > a:link,
.table_footer > a:visited,
{ color: grey;
    text-decoration: none;
}

.index { text-align: left; }

.mode_btn_selected {
  font-style: italic;
}

/* subroutine dispatch table */
td.sub_pkg {
  text-align: right;
  padding-right: 0;
  border-right: hidden;
  font-family: monospace;
  color: grey;
}

td.sub_sub {
  text-align: left;
  padding-left: 0;
  border-left: hidden;
  font-family: monospace;
}

a.sub_sub:link {
  color: blue;
  text-decoration: none;
}

a.sub_sub:hover,
a.sub_sub:visited:hover {
  text-decoration: underline;
}

a.sub_sub:visited, 
a.sub_sub:active {
  color: blue;
  text-decoration: none;
}

/* source code */
th.left_indent_header {
  padding-left: 15px;
  text-align: left;
}

pre,.s {
    text-align: left;
    font-family: monospace;
    white-space: pre;
}
/* plain number */
.n { text-align: right }

/* Classes for color-coding profiling information:
 *   c0  : code not hit
 *   c1  : coverage >= 75%
 *   c2  : coverage >= 90%
 *   c3  : path covered or coverage = 100%
 */
.c0, .c1, .c2, .c3 { text-align: right; }
.c0 {
    background-color: #ff9999;
}
.c1 {
    background-color: #ffcc99;
}
.c2 {
    background-color: #ffff99;
}
.c3 {
    background-color: #99ff99;
}

/* warnings */
.warn {
    background-color: #FFFFAA;
    border: 0;
    width: 96%;
    text-align: center;
    padding: 5px 0;
}

.warn_title {
    background-color: #FFFFAA;
    border: 0;
    color: red;
    width: 96%;
    font-size: 2em;
    text-align: center;
    padding: 5px 0;
}

.calls {
  display: block;
  color: grey;
  padding-top: 5px;
  padding-bottom: 5px;
  text-decoration: none;
}
.calls:hover {
    background-color: #e8e8e8;
    color: black;
}
.calls       a       { color: grey;  text-decoration: none; }
.calls:hover a       { color: black; text-decoration: underline; }
.calls:hover a:hover { color: red; }

__END__

=head1 NAME

nytprofhtml - Generate reports from Devel::NYTProf data

=head1 SYNOPSIS

Typical usage:

 $ perl -d:NYTProf some_perl_app.pl

 $ nytprofhtml
 Generating HTML Output...

 $ open nytprof/index.html

Options synopsis:

 $ nytprofhtml [-h] [-d] [-o <output directory>] [-f <input file>]

=head1 DESCRIPTION

Devel::NYTProf is a powerful feature-rich perl source code profiler.
See L<Devel::NYTProf> for details.

C<nytprofhtml> generates html a set of html reports from the data collected by
L<Devel::NYTProf>.

The reports include dynamic runtime analysis wherein each line and each file
is analyzed based on the preformance of the other lines and files.  As a
result, you can quickly find the slowest module and the slowest line in a 
module.  Slowness is measured in three ways: total calls, total time and
average time per call.

Coloring is based on absolute deviations from the median.
See L<http://en.wikipedia.org/wiki/Median_absolute_deviation> for more details.

That might sound complicated, but in reality you can just run the command and
enjoy your report!

=head1 COMMAND-LINE OPTIONS

=over 4

=item -f, --file <filename>

Specifies the location of the file generated by L<Devel::NYTProf>.
Default: ./nytprof.out

=item -o, --out <dir>

The directory in which to place the generated report files. Default: ./nytprof/

=item -d, --delete

Purge any existing contents of the report output directory.

=item -l, --lib <dir>

Add a path to the beginning of @INC to help nytprofhtml find the source files
used by the code. Should not be needed in practice.

=item -h, --help

Print the help message

=back

=head1 SAMPLE OUTPUT

You can see a complete report for a large application (over 200 files and 2000 subroutines) at
L<http://idisk.mac.com/tim.bunce-Public/perl/NYTProf/nytprof-perlcritic-20080812/index.html>

The report was generated by profiling L<perlcritic> 1.088 checking it's own source code.

=head1 HISTORY

A bit of history and a shameless plug...

NYTProf stands for 'New York Times Profiler'. Indeed, this module was initially
developed from Devel::FastProf by The New York Times Co. to help our developers
quickly identify bottlenecks in large Perl applications.  The NY Times loves
Perl and we hope the community will benefit from our work as much as we have
from theirs.

Please visit L<http://open.nytimes.com>, our open source blog to see what we
are up to, L<http://code.nytimes.com> to see some of our open projects and then
check out L<http://nytimes.com> for the latest news!

=head2 Background

Subroutine-level profilers:

  Devel::DProf        | 1995-10-31 | ILYAZ
  Devel::AutoProfiler | 2002-04-07 | GSLONDON
  Devel::Profiler     | 2002-05-20 | SAMTREGAR
  Devel::Profile      | 2003-04-13 | JAW
  Devel::DProfLB      | 2006-05-11 | JAW
  Devel::WxProf       | 2008-04-14 | MKUTTER

Statement-level profilers:

  Devel::SmallProf    | 1997-07-30 | ASHTED
  Devel::FastProf     | 2005-09-20 | SALVA
  Devel::NYTProf      | 2008-03-04 | AKAPLAN
  Devel::Profit       | 2008-05-19 | LBROCARD

Devel::NYTProf is a (now distant) fork of Devel::FastProf, which was itself an
evolution of Devel::SmallProf.

Adam Kaplan took Devel::FastProf and added html report generation (based on
Devel::Cover) and a test suite - a tricky thing to do for a profiler.
Meanwhile Tim Bunce had been extending Devel::FastProf to add novel
per-sub and per-block timing, plus subroutine caller tracking.

When Devel::NYTProf was released Tim switched to working on Devel::NYTProf
because the html report would be a good way to show the extra profile data, and
the test suite made development much easier and safer.

Then he went a little crazy and added a slew of new features, in addition to
per-sub and per-block timing and subroutine caller tracking. These included the
'opcode interception' method of profiling, ultra-fast and robust inclusive
subroutine timing, doubling performance, plus major changes to html reporting
to display all the extra profile call and timing data in richly annotated and
cross-linked reports.

Steve Peters came on board along the way with patches for portability and to
keep NYTProf working with the latest development perl versions.

Adam's work is sponsored by The New York Times Co. L<http://open.nytimes.com>.
Tim's work was partly sponsored by Shopzilla. L<http://www.shopzilla.com>.

=head1 SEE ALSO

Mailing list and discussion at L<http://groups.google.com/group/develnytprof-dev>

Public SVN Repository and hacking instructions at L<http://code.google.com/p/perl-devel-nytprof/>

L<Devel::NYTProf>,
L<Devel::NYTProf::Reader>,
L<nytprofcsv>

=head1 AUTHOR

B<Adam Kaplan>, C<< <akaplan at nytimes.com> >>.
B<Tim Bunce>, L<http://www.tim.bunce.name> and L<http://blog.timbunce.org>.
B<Steve Peters>, C<< <steve at fisharerojo.org> >>.

=head1 COPYRIGHT AND LICENSE

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.

=cut

# vim:ts=8:sw=4:expandtab
