perl 代码优化 - 查找需要优化的部分

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

1. time

shell>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>perl -d:DProf test.pl
shell>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>perl -d:SmallProf test.pl

shell>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>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' => sub { ...code1... },
'after' => sub { ...code2... },
});

上面这些模块的详细说明见各自的文档。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值