blib/lib/Devel/FileProfile.pm untested

filter: Statementstmt 0.0% 0 / 72 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 130 CC 18 SCAR 39.2
CC
18
Cov
0%
scalenum
90.0
END
42.0
ticktock
20.0
CRAP 50.3
1  
2 package Devel::FileProfile;
3  
4 use Time::HiRes qw(alarm time);
5  
6 my $looplen = 5000;
7 my $freq = 0.01;
8 my $context = 7;
9 my $started = 0;
10 my %files;
11 my %hits;
12 my $hits = 0;
13 my $done = 0;
14  
15 our $VERSION = 0.22;
16  
17 sub start
18 {
19 return if $started++;
20 $main::SIG{ALRM} = \&ticktock;
21 my $t1 = time;
22 for my $i (0..$looplen) {
23 sprintf("%-10d", $i);
24 }
25 my $t2 = time;
26 $freq = $t2 - $t1;
27 alarm($freq);
28 }
29  
30 sub import
31 {
32 my ($pkg, $file, $line) = caller();
33 $files{$file} = $line;
34 start();
35 }
36  
37 sub ticktock
38 {
39 my $i = 0;
40 my %done;
41 while(my ($pkg, $file, $line) = caller($i++)) {
42 next unless $files{$file};
43 next if $done{$file}{$line}++; # don't overcount recursion
44 $hits{$file}{$line}++;
45 }
46 $hits++;
47 alarm($freq) unless $done;
48 }
49  
50 sub END
51 {
52 print STDERR "# BEGIN PROFILE DATA\n";
53 printf STDERR "# SAMPLE RATE = %.4f seconds\n", $freq;
54  
55 $done = 1;
56  
57 for my $file (sort keys %hits) {
58 my @lines = sort { $a <=> $b } keys %{$hits{$file}};
59 print STDERR "########### $file\n";
60 local(*FILE);
61 open(FILE, "<$file") || die "open $file: $!";
62 my $line = 0;
63 my $last = 0;
64 while(<FILE>) {
65 $line++;
66 next if $line < $lines[0] - $context;
67 shift(@lines) while @lines and $line > $lines[0]+$context;
68 last unless @lines;
69 next if $line > $lines[0] + $context;
70 print "\n" if $last and ! ($last + 1 == $line);
71 if ($hits{$file}{$line}) {
72 printf STDERR "%-4s %-10d %s", scalenum($hits{$file}{$line}/$hits*100), $line, $_;
73 } else {
74 printf STDERR " %-10d %s", $line, $_;
75 }
76 $last = $line;
77 }
78 }
79 print STDERR "# END PROFILE DATA\n";
80 }
81  
82 # 0.04
83 # 0.37
84 # 3.73
85 # 37.3
86 # 3731
87 # 3.7K
88 # 37K
89 # 370K
90  
91 sub scalenum
92 {
93 my ($num) = @_;
94 die if $num < 0;
95 if ($num < 100) {
96 return int($num) if $num - int($num) < 0.00001;
97 return int($num+1) if $num + 0.00001 > int($num+1);
98 return sprintf("%.2f", $num) if $num < 10;
99 return sprintf("%.1f", $num);
100 }
101 return int($num+0.000001) if $num < 9999.9999;
102 my (@syms) = qw(K M G T P E Z Y);
103 while(1) {
104 $num /= 1000;
105 if ($num < 10) {
106 return sprintf("%.1f%s", $num, $syms[0]);
107 } elsif ($num < 1000) {
108 return sprintf("%d%s", $num, $sym[0]);
109 } else {
110 shift(@syms);
111 }
112 }
113 }
114  
115 1;
116  
117 __END__