Re: [問題] 逐行處理大檔有更快的方法嗎

看板Perl作者 (c9s)時間16年前 (2009/04/26 12:03), 編輯推噓4(402)
留言6則, 5人參與, 最新討論串3/5 (看更多)
$/ 或稱 $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
補充一下未使用 $/ 而用 my @lines =<FH>; 則會慢十倍以
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
可是他的需求是逐行處理..這個作法不就變得跟read()一樣?
04/29 02:53, 5F

04/29 09:04, , 6F
你可以讀進來之後再用 re 找到要處理的部份處理就好啦
04/29 09:04, 6F
文章代碼(AID): #19yzqSpR (Perl)
文章代碼(AID): #19yzqSpR (Perl)