在Haskell中高效地解析ASCII文件

前端之家收集整理的这篇文章主要介绍了在Haskell中高效地解析ASCII文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在 Haskell中重新实现一些我的ASCII解析器,因为我以为我可以获得一些速度.然而,即使一个简单的“grep和count”比 Python的一个恶作剧慢得多.

有人可以解释一下为什么以及如何正确执行?

所以任务是计算以字符串“foo”开头的行.

我的基本Python实现:

  1. with open("foo.txt",'r') as f:
  2. print len([line for line in f.readlines() if line.startswith('foo')])

和Haskell版本:

  1. import System.IO
  2. import Data.List
  3.  
  4. countFoos :: String -> Int
  5. countFoos str = length $filter (isPrefixOf "foo") (lines str)
  6.  
  7. main = do
  8. contents <- readFile "foo.txt"
  9. putStr (show $countFoos contents)

运行时间在一个〜600MB的文件与17001895行显示,Python实现几乎比Haskell一个快四倍(运行在我的MacBook Pro Retina 2015与PCIe SSD):

  1. > $time ./FooCounter
  2. 1770./FooCounter 20.92s user 0.62s system 98% cpu 21.858 total
  3.  
  4. > $time python foo_counter.py
  5. 1770
  6. python foo_counter.py 5.19s user 1.01s system 97% cpu 6.332 total

与unix命令行工具相比:

  1. > $time grep -c foo foo.txt
  2. 1770
  3. grep -c foo foo.txt 4.87s user 0.10s system 99% cpu 4.972 total
  4.  
  5. > $time fgrep -c foo foo.txt
  6. 1770
  7. fgrep -c foo foo.txt 6.21s user 0.10s system 99% cpu 6.319 total
  8.  
  9. > $time egrep -c foo foo.txt
  10. 1770
  11. egrep -c foo foo.txt 6.21s user 0.11s system 99% cpu 6.317 total

有任何想法吗?

更新:

使用AndrásKovács的实现(ByteString),我得到了半秒钟!

  1. > $time ./FooCounter
  2. 1770
  3. ./EvtReader 0.47s user 0.48s system 97% cpu 0.964 total

解决方法

我对以下解决方案进行了基准测试:
  1. {-# LANGUAGE OverloadedStrings #-}
  2.  
  3. import qualified Data.ByteString.Char8 as B
  4.  
  5. main =
  6. print . length . filter (B.isPrefixOf "foo") . B.lines =<< B.readFile "test.txt"

text.txt是一个具有800万行的170 MB文件,一半的行以“foo”开头.我编译了GHC 7.10和-O2 -fllvm.

ByteString版本的运行时间为0.27秒,而原始版本的运行时间为5.16秒.

但是,严格的ByteString版本使用170 MB内存加载完整的文件.将导入更改为Data.ByteString.Lazy.Char8我有0.39秒运行时和1 MB内存使用.

猜你在找的HTML相关文章