Why is this Haskell program so much slower than an equivalent Python one?

前端 未结 3 1565
春和景丽
春和景丽 2021-02-03 17:52

As part of a programming challenge, I need to read, from stdin, a sequence of space-separated integers (on a single line), and print the sum of those integers to stdout

3条回答
  •  不要未来只要你来
    2021-02-03 18:21

    read is slow. For bulk parsing, use bytestring or text primitives, or attoparsec.

    I did some benchmarking. Your original version ran in 23,9 secs on my computer. The version below ran in 0.35 secs:

    import qualified Data.ByteString.Char8 as B
    import Control.Applicative
    import Data.Maybe
    import Data.List
    import Data.Char
    
    main = print . sum =<< getIntList
    
    getIntList :: IO [Int]
    getIntList =
        map (fst . fromJust . B.readInt) . B.words <$> B.readFile "test.txt"
    

    By specializing the parser to your test.txt file, I could get the runtime down to 0.26 sec:

    getIntList :: IO [Int]          
    getIntList =
        unfoldr (B.readInt . B.dropWhile (==' ')) <$> B.readFile "test.txt"
    

提交回复
热议问题