【问题标题】:Haskell More efficient way to parse file of lines of digitsHaskell 解析数字行文件的更有效方法
【发布时间】:2012-07-04 09:06:12
【问题描述】:

所以我有一个大约 8mb 的文件,每个文件有 6 个整数,用空格分隔。

我目前的解析方法是:

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

并在

上映射到Ints
liftM lines . readFile

这将返回一个元组列表。但是,当我运行它时,加载文件并解析它需要将近 25 秒。有什么办法可以加快速度吗?该文件只是纯文本。

【问题讨论】:

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

标签: haskell


【解决方案1】:

您可以使用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

所以解析显然确实花费了大量时间。

【讨论】:

  • 谢谢。我忘记了haskell Lazy评估,所以我对时间问题的来源是错误的。但也感谢其他方法!
  • 你能用read展示实现0.66s的整个程序吗?我之前有asked a similar question,答案是“阅读速度很慢”。在这里,仅将read 替换为foldl (\a c -&gt; a*10 + fromEnum c - fromEnum '0') 0 就可以将速度提高6 倍,这表明解析确实花费了大部分时间。您是如何改进的?
猜你喜欢
  • 2018-12-31
  • 2015-10-05
  • 2021-12-29
  • 2019-03-11
  • 2017-03-06
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 2020-11-26
相关资源
最近更新 更多