[Perl Other] 快些,在快些,perl的小优化

Dec 20th, 2009

转载本站文章请注明,转载自:扶凯[http://www.php-oa.com]

本文链接: http://www.php-oa.com/2009/12/20/perl%e5%bf%ab%e4%ba%9b%e5%9c%a8%e5%bf%ab%e4%ba%9bperl%e7%9a%84%e5%b0%8f%e4%bc%98%e5%8c%96.html

一个小程序的简单优化,经过大师指点后速度的分别

[root@localhost ~]# time cat 5000 |perl check.pl  >/tmp/b

real    5m59.953s
user    5m59.956s
sys     0m0.105s
[root@localhost ~]# time cat 5000 |perl check1.pl  >/tmp/a

real    0m0.134s
user    0m0.111s
sys     0m0.030s

下面是程序优化后的check.pl

#!/usr/bin/perl
use strict;
use warnings;

open A,"){
        my ($md5,$ip) = split;
        $hash{$md5} = $ip;
}
while (<>){
    my $line = $_;
    if( /http:\/\/[\w.]+\/\d+\/(\w+)\// ){
        if( exists $hash{$1}){
            print $line."\n";
        }
    }
}

优化 前的

#!/usr/bin/perl
use strict;
use warnings;

open A,"){
        my ($md5,$ip) = split;
            $hash{$md5} = $ip;
        }
while (<>){
   my $line = $_;
      foreach my $md5 ( keys %hash){
              if($line =~ /$md5/){
                    print $line."\n";
                }
      }
}

在logan中有1W的记录.cat时有5k的行.发现正则的性能实在太好,然后使用keys来取hash查所有的表,反到性能不好,但是查是否存在,hash优化的相当于的不错.

Del.icio.us Google书签 Digg Live Bookmark Technorati Furl Yahoo书签 Facebook 百度搜藏 新浪 ViVi 365Key 网摘 天极网摘 和讯网摘 博拉网 POCO 网摘 饭否 QQ 书签 Digbuzz 我挖网 Mister Wong
Tags: ,
  1. XEEN
    Nov 4th, 2011 at 00:17
    Reply | Quote | #1

    相当的不错