Re: [問題] 逐行處理大檔有更快的方法嗎
$/ 或稱 $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
推
04/26 12:11, , 1F
04/26 12:11, 1F
→
04/26 12:26, , 2F
04/26 12:26, 2F
推
04/27 00:42, , 3F
04/27 00:42, 3F
推
04/27 21:22, , 4F
04/27 21:22, 4F
推
04/29 02:53, , 5F
04/29 02:53, 5F
→
04/29 09:04, , 6F
04/29 09:04, 6F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 5 篇):
Perl 近期熱門文章
PTT數位生活區 即時熱門文章