您可以使用ByteStrings 来加快速度,例如
module Main (main) where
import System.Environment (getArgs)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Char
main :: IO ()
main = do
args <- getArgs
mapM_ doFile args
doFile :: FilePath -> IO ()
doFile file = do
bs <- C.readFile file
let tups = buildTups 0 [] $ C.dropWhile (not . isDigit) bs
print (length tups)
buildTups :: Int -> [Int] -> C.ByteString -> [(Int,Int,Int,Int,Int,Int)]
buildTups 6 acc bs = tuplify6 acc : buildTups 0 [] bs
buildTups k acc bs
| C.null bs = if k == 0 then [] else error ("Bad file format " ++ show k)
| otherwise = case C.readInt bs of
Just (i,rm) -> buildTups (k+1) (i:acc) $ C.dropWhile (not . isDigit) rm
Nothing -> error ("No Int found: " ++ show (C.take 100 bs))
tuplify6:: [a] -> (a, a, a, a, a, a)
tuplify6 [l, m, n, o, p, q] = (l, m, n, o, p, q)
跑得很快:
$ time ./fileParse IntList
200000
real 0m0.119s
user 0m0.115s
sys 0m0.003s
对于 8.1 MiB 文件。
另一方面,使用Strings 和你的转换(用几个seqs 来强制评估)也只用了0.66s,所以大部分时间似乎都花在不解析上,但使用结果。
糟糕,错过了seq,因此reads 实际上并未针对String 版本进行评估。解决这个问题,String + read 大约需要 4 秒,比 @Rotsor 评论中的自定义 Int 解析器略高于 1 秒
foldl' (\a c -> 10*a + fromEnum c - fromEnum '0') 0
所以解析显然确实花费了大量时间。