---
title: "perl 代码优化 - 查找需要优化的部分"
author: "jedy"
date: "2006-12-22T03:47:00Z"
tags: []
slug: "perl"
draft: false
lastmod: "2006-12-22T03:47:00Z"
id: 304714
url: "https://jedy.iteye.com/blog/304714"
---

做代码优化首先要知道程序各部分的速度，什么地方最慢，最需要优化。  
下面有几种方法可以用于调查程序各部分的速度。

1\. time

shell&gt;time perl script.pl

这样可以得到程序的运行时间。

2\. Time::HiRes  
使用模块Time::HiRes中的函数gettimeofday，gettimeofday  
例：

for (xxx) {  
\# code 1  
$t0 = \[gettimeofday];  
\# code 2  
$elapsed = tv\_interval ( $t0 );  
$t += $slapsed;  
\# code 3  
}

这样$t中就是代码段code 2在程序中执行总共需要的时间。这个结果是精确到微秒的。

3\. Devel::DProf

\# test.pl  
sub d {  
print 1;  
}

sub g{  
print 1 for 1..10;  
}

sub f {  
print 2;  
}

for (1..10000){  
d();  
g();  
f();  
g();  
}

\# script end

shell&gt;perl -d:DProf test.pl  
shell&gt;dprofpp  
Total Elapsed Time = 0.289990 Seconds  
User+System Time = 0.269990 Seconds  
Exclusive Times  
%Time ExclSec CumulS #Calls sec/call Csec/c Name  
85.1 0.230 0.230 20000 0.0000 0.0000 main::g  
14.8 0.040 0.040 10000 0.0000 0.0000 main::f  
11.1 0.030 0.030 10000 0.0000 0.0000 main::d

4\. Devel::SmallProf  
shell&gt;perl -d:SmallProf test.pl

shell&gt;cat smallprof.out  
\================ SmallProf version 1.15 ================  
Profile of a.pl Page 1  
\=================================================================  
count wall tm cpu time line  
10000 0.000000 0.000000 1:sub d {  
10000 0.062426 0.090000 2:print 1;  
0 0.000000 0.000000 3:}  
0 0.000000 0.000000 4:  
20000 0.000000 0.000000 5:sub g{  
40000 0.390327 0.550000 6:print 1 for 1..10;  
0 0.000000 0.000000 7:}  
0 0.000000 0.000000 8:  
10000 0.000000 0.000000 9:sub f {  
10000 0.061660 0.100000 10:print 2;  
0 0.000000 0.000000 11:}  
0 0.000000 0.000000 12:  
1 0.000006 0.000000 13:for (1..10000){  
10000 0.036328 0.090000 14:d();  
10000 0.037353 0.160000 15:g();  
10000 0.038129 0.220000 16:f();  
10000 0.038368 0.150000 17:g();  
0 0.000000 0.000000 18:}  
0 0.000000 0.000000 19:

shell&gt;sort -k 2nr,2 smallprof.out  
40000 0.390327 0.550000 6:print 1 for 1..10;  
10000 0.062426 0.090000 2:print 1;  
10000 0.061660 0.100000 10:print 2;  
10000 0.038368 0.150000 17:g();  
10000 0.038129 0.220000 16:f();  
10000 0.037353 0.160000 15:g();  
10000 0.036328 0.090000 14:d();  
1 0.000006 0.000000 13:for (1..10000){  
\=================================================================  
0 0.000000 0.000000 11:}  
0 0.000000 0.000000 12:  
0 0.000000 0.000000 18:}  
0 0.000000 0.000000 19:  
0 0.000000 0.000000 3:}  
0 0.000000 0.000000 4:  
0 0.000000 0.000000 7:}  
0 0.000000 0.000000 8:  
10000 0.000000 0.000000 1:sub d {  
10000 0.000000 0.000000 9:sub f {  
20000 0.000000 0.000000 5:sub g{  
count wall tm cpu time line  
Profile of a.pl Page 1  
\================ SmallProf version 1.15 ================

程序改进之后如果想知道效果如何，可以使用模块Benchmark。  
例:

use Benchmark qw/timethse/;  
timethese($count, {  
'before' =&gt; sub { ...code1... },  
'after' =&gt; sub { ...code2... },  
});

上面这些模块的详细说明见各自的文档。