2012-07-03 25 views
7

所以我有一个约8mb的文件,每个文件有6个整数,由一个空格分隔。Haskell更有效的方法来解析文件的位数

我解析这个电流的方法是:

tuplify6 :: [a] -> (a, a, a, a, a, a) 
tuplify6 [l, m, n, o, p, q] = (l, m, n, o, p, q) 

toInts :: String -> (Int, Int, Int, Int, Int, Int) 
toInts line = 
     tuplify6 $ map read stringNumbers 
     where stringNumbers = split " " line 

和映射toInts超过

liftM lines . readFile 

将返回我的元组的列表。但是,当我运行这个时,它需要将近25秒来加载文件并解析它。任何方式,我可以加快这一点?该文件只是纯文本。

+0

您能否提供更多信息:整个工作程序,输入,运行方式,编译方式(优化)还是在'ghci'中运行。你知道'Data.Bytestring'和'Data.Vector'。另外'读'是很慢,至少这是我所听到的。 – epsilonhalbe

+0

另请参阅http://stackoverflow.com/questions/8366093/how-do-i-parse-a-matrix-of-integers-in-haskell/8366642 –

回答

8

您可以使用ByteString s来加快速度,例如,

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文件。

在另一方面,使用String S和转换(一对夫妇的seq s到强制评估)也只用了0.66s,这样的时间大部分似乎花费不解析,但与工作结果。

糟糕,错过了seq因此read s没有实际评估String版本。固定的是,String + read需要大约四秒钟,略高于一个与自定义Int解析器@ Rotsor的评论

foldl' (\a c -> 10*a + fromEnum c - fromEnum '0') 0 

这样解析显然没有走的时间显著量。

+0

谢谢。我忘记了haskell惰性评估,所以我错在时间问题的来源。但是也要感谢其他方法! – DantheMan

+0

你可以用'read'来显示完成0.66s的整个程序吗?我[问过类似的问题](http://stackoverflow.com/questions/7510078/why-is-char-based-input-so-much-slower-than-the-char-based-output-in-哈斯克尔)之前,答案是“阅读缓慢”。在这里,仅仅用'foldl(\ a c - > a * 10 + fromEnum c - fromEnum'0')替换'read'会使速度提高6倍,表明大部分时间都是通过解析来实现的。你是如何设法改进的? – Rotsor

相关问题