作者kornelius (c9s)
看板Perl
标题Re: [问题] 逐行处理大档有更快的方法吗
时间Sun Apr 26 12:03:37 2009
$/ 或称 $INPUT_RECORD_SEPARATOR 或称 $RS
预设 $/ 为 \n (newline)
也就是 <FILE> 时读档遇到 \n 就中断传回一行
local $/; 时 $/ 为 undef
会启用 slurp 模式
所以会读满整个档案
当然如果你想指定 byte size 也是可以。
请参考 perldoc -v $/ ( 需安装 Pod::Perldoc 模组才能搜寻变数 )
perldoc 如是说:
Setting $/ to a reference to an integer, scalar containing an
integer, or scalar that's convertible to an integer will
attempt to read records instead of lines, with the maximum
record size being the referenced integer. So this:
local $/ = \32768; # or \"32768", or \$var_containing_32768
open my $fh, $myfile or die $!;
local $_ = <$fh>;
will read a record of no more than 32768 bytes from FILE.
刚刚又换更大档案测试了一下
使用 slurp mode 读 150MB 的档案仍是比不用 slurp mode 快一倍。
※ 引述《kornelius (c9s)》之铭言:
: 利用 local $/ 可以改善一些效能。
: 如果资讯处理的部份会托慢速度,你可以考虑把那个部份切成 thread 做
: 或是 pipe 出去给其他多个 process
: 我用一个大约 15M random file 做了一下测试:
: [ Oulixeus :~ ]$ time perl chunk.pl
: real 0m0.130s
: user 0m0.094s
: sys 0m0.029s
: [ Oulixeus :~ ]$ time perl chunk.pl # 加上 local $/;
: real 0m0.071s
: user 0m0.018s
: sys 0m0.046s
--
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 122.117.168.163
1F:推 abliou:推 ! 04/26 12:11
2F:→ kornelius:补充一下未使用 $/ 而用 my @lines =<FH>; 则会慢十倍以 04/26 12:26
3F:推 teyton:原来还有这招!! 受教了,感谢!! 04/27 00:42
4F:推 cot123:推 04/27 21:22
5F:推 jackieku:可是他的需求是逐行处理..这个作法不就变得跟read()一样? 04/29 02:53
6F:→ kornelius:你可以读进来之後再用 re 找到要处理的部份处理就好啦 04/29 09:04