大佬教程收集整理的这篇文章主要介绍了在Haskell中高效地解析ASCII文件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释一下为什么以及如何正确执行?
所以任务是计算以字符串“foo”开头的行.
我的基本Python实现:
with open("foo.txt",'r') as f: print len([line for line in f.readlines() if line.startswith('foo')])
和Haskell版本:
import System.IO import Data.List countFoos :: String -> Int countFoos str = length $filter (isPrefixOf "foo") (lines str) main = do contents <- readFile "foo.txt" putStr (show $countFoos contents)
运行时间在一个〜600MB的文件与17001895行显示,Python实现几乎比Haskell一个快四倍(运行在我的MACBook Pro ReTina 2015与PCIe SSD):
> $time ./FooCounter 1770./FooCounter 20.92s user 0.62s system 98% cpu 21.858 @R_694_10586@l > $time python foo_counter.py 1770 python foo_counter.py 5.19s user 1.01s system 97% cpu 6.332 @R_694_10586@l
与unix命令行工具相比:
> $time grep -c foo foo.txt 1770 grep -c foo foo.txt 4.87s user 0.10s system 99% cpu 4.972 @R_694_10586@l > $time fgrep -c foo foo.txt 1770 fgrep -c foo foo.txt 6.21s user 0.10s system 99% cpu 6.319 @R_694_10586@l > $time egrep -c foo foo.txt 1770 egrep -c foo foo.txt 6.21s user 0.11s system 99% cpu 6.317 @R_694_10586@l
有任何想法吗?
更新:
使用AndrásKovács的实现(ByteString),我得到了半秒钟!
> $time ./FooCounter 1770 ./EvtReader 0.47s user 0.48s system 97% cpu 0.964 @R_694_10586@l
{-# LANGUAGE OverloadedStrings #-} import qualified Data.byteString.Char8 as B main = 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内存使用.
以上是大佬教程为你收集整理的在Haskell中高效地解析ASCII文件全部内容,希望文章能够帮你解决在Haskell中高效地解析ASCII文件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。