免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4022 | 回复: 2
打印 上一主题 下一主题

为什么这个正则处理表达式速度太慢? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-09-14 10:09 |只看该作者 |倒序浏览
如下程序只是将一段字符串每隔8个字符加入回车换行,但如内容为几十K的话,要半分钟,为2M的话,
几分钟都不能处理完成.为什么?该如何修改?


#! perl -w
$infile = "MENU.FNT";
$outfile = ">"."fontshow1.txt";


open(INPUT_FILE, $infile) || die "Can not open file $infile !";
open(OUT_FILE, $outfile) || die "Can not open file $outfile !";

binmode INPUT_FILE;
binmode OUT_FILE;

$txt="";
while(read(INPUT_FILE, $buf, 32*32*1024))
{
        $txt .= $buf;
}


$hexstr = unpack ('H*', $txt);

$txt = $hexstr;


$txt =~ s/(.{8})/$1\r\n/g;  #将一段字符串每隔8个字符加入回车换行

..................

#print $txt;
print OUT_FILE $txt;

close(INPUT_FILE);
close(OUT_FILE);

求职 : 软件工程师
论坛徽章:
3
程序设计版块每日发帖之星
日期:2015-10-07 06:20:00程序设计版块每日发帖之星
日期:2015-12-13 06:20:00程序设计版块每日发帖之星
日期:2016-05-05 06:20:00
2 [报告]
发表于 2013-09-14 11:04 |只看该作者
  1. #!perl

  2. use File::Slurp qw(read_file write_file);

  3. my @chars = split //, read_file("MENU.FNT");
  4. my $count = 0;
  5. foreach my $char (@chars) {
  6.         $count++;
  7.         push @new_chars, $char;
  8.         push @new_chars, chr(10) if ($count % 4 == 0);
  9. }

  10. write_file("fontshow1.txt", join('', @new_chars));
复制代码

论坛徽章:
145
技术图书徽章
日期:2013-10-01 15:32:13戌狗
日期:2013-10-25 13:31:35金牛座
日期:2013-11-04 16:22:07子鼠
日期:2013-11-18 18:48:57白羊座
日期:2013-11-29 10:09:11狮子座
日期:2013-12-12 09:57:42白羊座
日期:2013-12-24 16:24:46辰龙
日期:2014-01-08 15:26:12技术图书徽章
日期:2014-01-17 13:24:40巳蛇
日期:2014-02-18 14:32:59未羊
日期:2014-02-20 14:12:13白羊座
日期:2014-02-26 12:06:59
3 [报告]
发表于 2013-09-14 12:48 |只看该作者
本帖最后由 jason680 于 2013-09-14 14:35 编辑

回复 1# oukm

modify from your code ...

$ wc MENU.FNT
1168463  3960509 58142720 MENU.FNT

$ time perl hex.pl
real        0m8.542s
user        0m4.032s
sys        0m3.216s

$ time perl hex1.pl  # your code
real        0m17.034s
user        0m4.772s
sys        0m9.557s

$ cat hex.pl
use strict;
use warnings;

my $infile = "MENU.FNT";
my $outfile = "fontshow1.txt";


open(FHin,  "<", $infile)  || die "Can not open file $infile !";
open(FHout, ">", $outfile) || die "Can not open file $outfile !";

binmode FHin;
binmode FHout;

while(my $sLen = read(FHin, my $sBuf, 32*32*1024))
{
  my $sTxt = unpack('H*', $sBuf);
  my $sCycle = int($sLen /4 ) + ($sLen %4 != 0) -1;
  my $sOut = "";
  foreach(0 .. $sCycle){
     $sOut .= substr($sTxt, $_*8, 8) . "\r\n";
  }
  print FHout "$sOut";

}

close(FHin);
close(FHout);

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP