home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / ProfileData.pm < prev    next >
Encoding:
Perl POD Document  |  2004-03-16  |  16.7 KB  |  642 lines

  1. package DBI::ProfileData;
  2. use strict;
  3.  
  4. =head1 NAME
  5.  
  6. DBI::ProfileData - manipulate DBI::ProfileDumper data dumps
  7.  
  8. =head1 SYNOPSIS
  9.  
  10. The easiest way to use this module is through the dbiprof frontend
  11. (see L<dbiprof> for details):
  12.  
  13.   dbiprof --number 15 --sort count
  14.  
  15. This module can also be used to roll your own profile analysis:
  16.  
  17.   # load data from dbi.prof
  18.   $prof = DBI::ProfileData->new(File => "dbi.prof");
  19.  
  20.   # get a count of the records in the data set
  21.   $count = $prof->count();
  22.  
  23.   # sort by longest overall time
  24.   $prof->sort(field => "longest");
  25.  
  26.   # sort by longest overall time, least to greatest
  27.   $prof->sort(field => "longest", reverse => 1);
  28.  
  29.   # exclude records with key2 eq 'disconnect'
  30.   $prof->exclude(key2 => 'disconnect');
  31.  
  32.   # exclude records with key1 matching /^UPDATE/i
  33.   $prof->exclude(key1 => qr/^UPDATE/i);
  34.  
  35.   # remove all records except those where key1 matches /^SELECT/i
  36.   $prof->match(key1 => qr/^SELECT/i);
  37.  
  38.   # produce a formatted report with the given number of items
  39.   $report = $prof->report(number => 10); 
  40.  
  41.   # clone the profile data set
  42.   $clone = $prof->clone();
  43.  
  44.   # get access to hash of header values
  45.   $header = $prof->header();
  46.  
  47.   # get access to sorted array of nodes
  48.   $nodes = $prof->nodes();
  49.  
  50.   # format a single node in the same style as report()
  51.   $text = $prof->format($nodes->[0]);
  52.  
  53.   # get access to Data hash in DBI::Profile format
  54.   $Data = $prof->Data();
  55.  
  56. =head1 DESCRIPTION
  57.  
  58. This module offers the ability to read, manipulate and format
  59. DBI::ProfileDumper profile data.  
  60.  
  61. Conceptually, a profile consists of a series of records, or nodes,
  62. each of each has a set of statistics and set of keys.  Each record
  63. must have a unique set of keys, but there is no requirement that every
  64. record have the same number of keys.
  65.  
  66. =head1 METHODS
  67.  
  68. The following methods are supported by DBI::ProfileData objects.
  69.  
  70. =over 4
  71.  
  72. =cut
  73.  
  74. use vars qw($VERSION);
  75. $VERSION = "1.0";
  76.  
  77. use Carp qw(croak);
  78. use Symbol;
  79.  
  80. use DBI::Profile qw(dbi_profile_merge);
  81.  
  82. # some constants for use with node data arrays
  83. sub COUNT     () { 0 };
  84. sub TOTAL     () { 1 };
  85. sub FIRST     () { 2 };
  86. sub SHORTEST  () { 3 };
  87. sub LONGEST   () { 4 };
  88. sub FIRST_AT  () { 5 };
  89. sub LAST_AT   () { 6 };
  90. sub PATH      () { 7 };
  91.  
  92. =item $prof = DBI::ProfileData->new(File => "dbi.prof")
  93.  
  94. =item $prof = DBI::ProfileData->new(Files => [ "dbi.prof.1", "dbi.prof.2" ])
  95.  
  96. Creates a a new DBI::ProfileData object.  Takes either a single file
  97. through the File option or a list of Files in an array ref.  If
  98. multiple files are specified then the header data from the first file
  99. is used.
  100.  
  101. =cut
  102.  
  103. sub new {
  104.     my $pkg = shift;
  105.     my $self = {                
  106.                 Files        => [ "dbi.prof" ],
  107.                 _header      => {},
  108.                 _nodes       => [],
  109.                 _node_lookup => {},
  110.                 @_
  111.                };
  112.     bless $self, $pkg;
  113.     
  114.     # File overrides Files
  115.     $self->{Files} = [ $self->{File} ] if exists $self->{File};
  116.  
  117.     $self->_read_files();
  118.     return $self;
  119. }
  120.  
  121. # read files into _header and _nodes
  122. sub _read_files {
  123.     my $self = shift;
  124.     my $files = $self->{Files};
  125.     my $read_header = 0;
  126.     
  127.     foreach my $filename (@$files) {
  128.         my $fh = gensym;
  129.         open($fh, $filename)
  130.           or croak("Unable to read profile file '$filename': $!");
  131.         
  132.         $self->_read_header($fh, $filename, $read_header ? 0 : 1);
  133.         $read_header = 1;
  134.         $self->_read_body($fh, $filename);
  135.         close($fh);
  136.     }
  137.     
  138.     # discard node_lookup now that all files are read
  139.     delete $self->{_node_lookup};
  140. }
  141.  
  142. # read the header from the given $fh named $filename.  Discards the
  143. # data unless $keep.
  144. sub _read_header {
  145.     my ($self, $fh, $filename, $keep) = @_;
  146.  
  147.     # get profiler module id
  148.     my $first = <$fh>;
  149.     chomp $first;
  150.     $self->{_profiler} = $first if $keep;
  151.  
  152.     # collect variables from the header
  153.     while (<$fh>) {
  154.         chomp;
  155.         last unless length $_;
  156.         /^(\S+)\s*=\s*(.*)/
  157.           or croak("Syntax error in header in $filename line $.: $_");
  158.         $self->{_header}{$1} = $2 if $keep;
  159.     }
  160. }
  161.  
  162. # reads the body of the profile data
  163. sub _read_body {
  164.     my ($self, $fh, $filename) = @_;
  165.     my $nodes = $self->{_nodes};
  166.     my $lookup = $self->{_node_lookup};
  167.  
  168.     # build up node array
  169.     my @path = ("");
  170.     my (@data, $index, $key, $path_key);
  171.     while (<$fh>) {
  172.         chomp;
  173.         if (/^\+\s+(\d+)\s?(.*)/) {
  174.             # it's a key
  175.             ($key, $index) = ($2, $1 - 1);
  176.  
  177.             # unmangle key
  178.             $key =~ s/(?<!\\)\\n/\n/g; # expand \n, unless it's a \\n
  179.             $key =~ s/(?<!\\)\\r/\r/g; # expand \r, unless it's a \\r
  180.             $key =~ s/\\\\/\\/g;       # \\ to \
  181.  
  182.             $#path = $index;      # truncate path to new length
  183.             $path[$index] = $key; # place new key at end
  184.  
  185.         }
  186.     elsif (/^=/) {
  187.             # it's data - file in the node array with the path in index 0
  188.             @data = /^=\s+(\d+)
  189.                        \s+(\d+\.?\d*)
  190.                        \s+(\d+\.?\d*)
  191.                        \s+(\d+\.?\d*)
  192.                        \s+(\d+\.?\d*)
  193.                        \s+(\d+\.?\d*)
  194.                        \s+(\d+\.?\d*)
  195.                        \s*$/x;
  196.  
  197.             # no data?
  198.             croak("Invalid data syntax format in $filename line $.: $_") unless @data;
  199.  
  200.             # elements of @path can't have NULLs in them, so this
  201.             # forms a unique string per @path.  If there's some way I
  202.             # can get this without arbitrarily stripping out a
  203.             # character I'd be happy to hear it!
  204.             $path_key = join("\0",@path);
  205.  
  206.             # look for previous entry
  207.             if (exists $lookup->{$path_key}) {
  208.                 # merge in the new data
  209.         dbi_profile_merge($nodes->[$lookup->{$path_key}], \@data);
  210.             } else {
  211.                 # insert a new node - nodes are arrays with data in 0-6
  212.                 # and path data after that
  213.                 push(@$nodes, [ @data, @path ]);
  214.  
  215.                 # record node in %seen
  216.                 $lookup->{$path_key} = $#$nodes;
  217.             }
  218.         }
  219.     else {
  220.             croak("Invalid line type syntax error in $filename line $.: $_");
  221.     }
  222.     }
  223. }
  224.  
  225. # takes an existing node and merges in new data points
  226. sub _merge_data {    # XXX use dbi_profile_merge instead
  227.     my ($self, $node, $data) = @_;
  228.  
  229.     # add counts and total duration
  230.     $node->[COUNT] += $data->[COUNT];
  231.     $node->[TOTAL] += $data->[TOTAL];
  232.     
  233.     # first duration untouched
  234.  
  235.     # take new shortest duration if shorter
  236.     $node->[SHORTEST] = $data->[SHORTEST]
  237.       if $data->[SHORTEST] < $node->[SHORTEST];
  238.  
  239.     # take new longest duration if longer
  240.     $node->[LONGEST] = $data->[LONGEST]
  241.       if $data->[LONGEST] > $node->[LONGEST];
  242.  
  243.     # time of first event untouched
  244.  
  245.     # take time of last event
  246.     $node->[LAST_AT] = $data->[LAST_AT];
  247. }
  248.  
  249.  
  250.  
  251. =item $copy = $prof->clone();
  252.  
  253. Clone a profile data set creating a new object.
  254.  
  255. =cut
  256.  
  257. sub clone {
  258.     my $self = shift;
  259.  
  260.     # start with a simple copy
  261.     my $clone = bless { %$self }, ref($self);
  262.  
  263.     # deep copy nodes
  264.     $clone->{_nodes}  = [ map { [ @$_ ] } @{$self->{_nodes}} ];
  265.  
  266.     # deep copy header
  267.     $clone->{_header} = { %{$self->{_header}} };
  268.  
  269.     return $clone;
  270. }
  271.  
  272. =item $header = $prof->header();
  273.  
  274. Returns a reference to a hash of header values.  These are the key
  275. value pairs included in the header section of the DBI::ProfileDumper
  276. data format.  For example:
  277.  
  278.   $header = {
  279.               Path    => '[ DBIprofile_Statement, DBIprofile_MethodName ]',
  280.               Program => 't/42profile_data.t',
  281.             };
  282.  
  283. Note that modifying this hash will modify the header data stored
  284. inside the profile object.
  285.  
  286. =cut
  287.  
  288. sub header { shift->{_header} }
  289.  
  290.  
  291. =item $nodes = $prof->nodes()
  292.  
  293. Returns a reference the sorted nodes array.  Each element in the array
  294. is a single record in the data set.  The first seven elements are the
  295. same as the elements provided by DBI::Profile.  After that each key is
  296. in a separate element.  For example:
  297.  
  298.  $nodes = [
  299.             [
  300.               2,                      # 0, count
  301.               0.0312958955764771,     # 1, total duration
  302.               0.000490069389343262,   # 2, first duration
  303.               0.000176072120666504,   # 3, shortest duration
  304.               0.00140702724456787,    # 4, longest duration
  305.               1023115819.83019,       # 5, time of first event
  306.               1023115819.86576,       # 6, time of last event
  307.               'SELECT foo FROM bar'   # 7, key1
  308.               'execute'               # 8, key2
  309.                                       # 6+N, keyN
  310.             ],
  311.                                       # ...
  312.           ];
  313.  
  314. Note that modifying this array will modify the node data stored inside
  315. the profile object.
  316.  
  317. =cut
  318.  
  319. sub nodes { shift->{_nodes} }
  320.  
  321. =item $count = $prof->count()
  322.  
  323. Returns the number of items in the profile data set.
  324.  
  325. =cut
  326.  
  327. sub count { scalar @{shift->{_nodes}} }
  328.  
  329. =item $prof->sort(field => "field")
  330.  
  331. =item $prof->sort(field => "field", reverse => 1)
  332.  
  333. Sorts data by the given field.  Available fields are:
  334.  
  335.   longest
  336.   total
  337.   count
  338.   shortest
  339.  
  340. The default sort is greatest to smallest, which is the opposite of the
  341. normal Perl meaning.  This, however, matches the expected behavior of
  342. the dbiprof frontend.
  343.  
  344. =cut
  345.  
  346.  
  347. # sorts data by one of the available fields
  348. {
  349.     my %FIELDS = (
  350.                   longest  => LONGEST,
  351.                   total    => TOTAL,
  352.                   count    => COUNT,
  353.                   shortest => SHORTEST,
  354.                  );
  355.     sub sort {
  356.         my $self = shift;
  357.         my $nodes = $self->{_nodes};
  358.         my %opt = @_;
  359.         
  360.         croak("Missing required field option.") unless $opt{field};
  361.  
  362.         my $index = $FIELDS{$opt{field}};
  363.         
  364.         croak("Unrecognized sort field '$opt{field}'.")
  365.           unless defined $index;
  366.  
  367.         # sort over index
  368.         if ($opt{reverse}) {
  369.             @$nodes = sort { 
  370.                 $a->[$index] <=> $b->[$index] 
  371.             } @$nodes;
  372.         } else {
  373.             @$nodes = sort { 
  374.                 $b->[$index] <=> $a->[$index] 
  375.             } @$nodes;
  376.         }
  377.  
  378.         # remember how we're sorted
  379.         $self->{_sort} = $opt{field};
  380.  
  381.         return $self;
  382.     }
  383. }
  384.  
  385. =item $count = $prof->exclude(key2 => "disconnect")
  386.  
  387. =item $count = $prof->exclude(key2 => "disconnect", case_sensitive => 1)
  388.  
  389. =item $count = $prof->exclude(key1 => qr/^SELECT/i)
  390.  
  391. Removes records from the data set that match the given string or
  392. regular expression.  This method modifies the data in a permanent
  393. fashion - use clone() first to maintain the original data after
  394. exclude().  Returns the number of nodes left in the profile data set.
  395.  
  396. =cut
  397.  
  398. sub exclude {
  399.     my $self = shift;
  400.     my $nodes = $self->{_nodes};
  401.     my %opt = @_;
  402.  
  403.     # find key index number
  404.     my ($index, $val);
  405.     foreach (keys %opt) {
  406.         if (/^key(\d+)$/) {
  407.             $index   = PATH + $1 - 1;
  408.             $val     = $opt{$_};
  409.             last;
  410.         }
  411.     }
  412.     croak("Missing required keyN option.") unless $index;
  413.  
  414.     if (UNIVERSAL::isa($val,"Regexp")) {
  415.         # regex match
  416.         @$nodes = grep {
  417.             $#$_ < $index or $_->[$index] !~ /$val/ 
  418.         } @$nodes;
  419.     } else {
  420.         if ($opt{case_sensitive}) {
  421.             @$nodes = grep { 
  422.                 $#$_ < $index or $_->[$index] ne $val;
  423.             } @$nodes;
  424.         } else {
  425.             $val = lc $val;
  426.             @$nodes = grep { 
  427.                 $#$_ < $index or lc($_->[$index]) ne $val;
  428.             } @$nodes;
  429.         }
  430.     }
  431.  
  432.     return scalar @$nodes;
  433. }
  434.  
  435.  
  436. =item $count = $prof->match(key2 => "disconnect")
  437.  
  438. =item $count = $prof->match(key2 => "disconnect", case_sensitive => 1)
  439.  
  440. =item $count = $prof->match(key1 => qr/^SELECT/i)
  441.  
  442. Removes records from the data set that do not match the given string
  443. or regular expression.  This method modifies the data in a permanent
  444. fashion - use clone() first to maintain the original data after
  445. match().  Returns the number of nodes left in the profile data set.
  446.  
  447. =cut
  448.  
  449. sub match {
  450.     my $self = shift;
  451.     my $nodes = $self->{_nodes};
  452.     my %opt = @_;
  453.  
  454.     # find key index number
  455.     my ($index, $val);
  456.     foreach (keys %opt) {
  457.         if (/^key(\d+)$/) {
  458.             $index   = PATH + $1 - 1;
  459.             $val     = $opt{$_};
  460.             last;
  461.         }
  462.     }
  463.     croak("Missing required keyN option.") unless $index;
  464.  
  465.     if (UNIVERSAL::isa($val,"Regexp")) {
  466.         # regex match
  467.         @$nodes = grep {
  468.             $#$_ >= $index and $_->[$index] =~ /$val/ 
  469.         } @$nodes;
  470.     } else {
  471.         if ($opt{case_sensitive}) {
  472.             @$nodes = grep { 
  473.                 $#$_ >= $index and $_->[$index] eq $val;
  474.             } @$nodes;
  475.         } else {
  476.             $val = lc $val;
  477.             @$nodes = grep { 
  478.                 $#$_ >= $index and lc($_->[$index]) eq $val;
  479.             } @$nodes;
  480.         }
  481.     }
  482.  
  483.     return scalar @$nodes;
  484. }
  485.  
  486. =item $Data = $prof->Data()
  487.  
  488. Returns the same Data hash structure as seen in DBI::Profile.  This
  489. structure is not sorted.  The nodes() structure probably makes more
  490. sense for most analysis.
  491.  
  492. =cut
  493.  
  494. sub Data {
  495.     my $self = shift;
  496.     my (%Data, @data, $ptr);
  497.  
  498.     foreach my $node (@{$self->{_nodes}}) {
  499.         # traverse to key location
  500.         $ptr = \%Data;
  501.         foreach my $key (@{$node}[PATH .. $#$node - 1]) {
  502.             $ptr->{$key} = {} unless exists $ptr->{$key};
  503.             $ptr = $ptr->{$key};
  504.         }
  505.  
  506.         # slice out node data
  507.         $ptr->{$node->[-1]} = [ @{$node}[0 .. 6] ];
  508.     }
  509.  
  510.     return \%Data;
  511. }
  512.  
  513. =item $text = $prof->format($nodes->[0])
  514.  
  515. Formats a single node into a human-readable block of text.
  516.  
  517. =cut
  518.  
  519. sub format {
  520.     my ($self, $node) = @_;
  521.     my $format;
  522.     
  523.     # setup keys
  524.     my $keys = "";
  525.     for (my $i = PATH; $i <= $#$node; $i++) {
  526.         my $key = $node->[$i];
  527.         
  528.         # remove leading and trailing space
  529.         $key =~ s/^\s+//;
  530.         $key =~ s/\s+$//;
  531.  
  532.         # if key has newlines or is long take special precautions
  533.         if (length($key) > 72 or $key =~ /\n/) {
  534.             $keys .= "  Key " . ($i - PATH + 1) . "         :\n\n$key\n\n";
  535.         } else {
  536.             $keys .= "  Key " . ($i - PATH + 1) . "         : $key\n";
  537.         }
  538.     }
  539.  
  540.     # nodes with multiple runs get the long entry format, nodes with
  541.     # just one run get a single count.
  542.     if ($node->[COUNT] > 1) {
  543.         $format = <<END;
  544.   Count         : %d
  545.   Total Time    : %3.6f seconds
  546.   Longest Time  : %3.6f seconds
  547.   Shortest Time : %3.6f seconds
  548.   Average Time  : %3.6f seconds
  549. END
  550.         return sprintf($format, @{$node}[COUNT,TOTAL,LONGEST,SHORTEST], 
  551.                        $node->[TOTAL] / $node->[COUNT]) . $keys;
  552.     } else {
  553.         $format = <<END;
  554.   Count         : %d
  555.   Time          : %3.6f seconds
  556. END
  557.  
  558.         return sprintf($format, @{$node}[COUNT,TOTAL]) . $keys;
  559.  
  560.     }
  561. }
  562.  
  563. =item $text = $prof->report(number => 10)
  564.  
  565. Produces a report with the given number of items.
  566.  
  567. =cut
  568.  
  569. sub report {
  570.     my $self  = shift;
  571.     my $nodes = $self->{_nodes};
  572.     my %opt   = @_;
  573.  
  574.     croak("Missing required number option") unless exists $opt{number};
  575.  
  576.     $opt{number} = @$nodes if @$nodes < $opt{number};
  577.  
  578.     my $report = $self->_report_header($opt{number});
  579.     for (0 .. $opt{number} - 1) {
  580.         $report .= sprintf("#" x 5  . "[ %d ]". "#" x 59 . "\n", 
  581.                            $_ + 1);
  582.         $report .= $self->format($nodes->[$_]);
  583.         $report .= "\n";
  584.     }
  585.     return $report;
  586. }
  587.  
  588. # format the header for report()
  589. sub _report_header {
  590.     my ($self, $number) = @_;
  591.     my $nodes = $self->{_nodes};
  592.     my $node_count = @$nodes;
  593.  
  594.     # find total runtime and method count
  595.     my ($time, $count) = (0,0);
  596.     foreach my $node (@$nodes) {
  597.         $time  += $node->[TOTAL];
  598.         $count += $node->[COUNT];
  599.     }
  600.  
  601.     my $header = <<END;
  602.  
  603. DBI Profile Data ($self->{_profiler})
  604.  
  605. END
  606.  
  607.     # output header fields
  608.     while (my ($key, $value) = each %{$self->{_header}}) {
  609.         $header .= sprintf("  %-13s : %s\n", $key, $value);
  610.     }
  611.  
  612.     # output summary data fields
  613.     $header .= sprintf(<<END, $node_count, $number, $self->{_sort}, $count, $time);
  614.   Total Records : %d (showing %d, sorted by %s)
  615.   Total Count   : %d
  616.   Total Runtime : %3.6f seconds  
  617.  
  618. END
  619.  
  620.     return $header;
  621. }
  622.  
  623.  
  624. 1;
  625.  
  626. __END__
  627.  
  628. =back
  629.  
  630. =head1 AUTHOR
  631.  
  632. Sam Tregar <sam@tregar.com>
  633.  
  634. =head1 COPYRIGHT AND LICENSE
  635.  
  636. Copyright (C) 2002 Sam Tregar
  637.  
  638. This program is free software; you can redistribute it and/or modify
  639. it under the same terms as Perl 5 itself.
  640.  
  641. =cut
  642.