Skip to content

Instantly share code, notes, and snippets.

@BoeingX
Created November 4, 2018 15:16
Show Gist options
  • Select an option

  • Save BoeingX/a4a67c03599c381d5f1371c1f073be39 to your computer and use it in GitHub Desktop.

Select an option

Save BoeingX/a4a67c03599c381d5f1371c1f073be39 to your computer and use it in GitHub Desktop.
Compare different ways from reading integers from standard input or a file
import Criterion.Main
import System.Environment
import qualified Data.ByteString.Char8 as C
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
readBaseline :: FilePath -> IO [Int]
readBaseline filename = map parse . words <$> readFile filename
where parse :: String -> Int
parse = read
readText :: FilePath -> IO [Int]
readText filename = map parse . T.words <$> T.readFile filename
where parse :: T.Text -> Int
parse s = let Right (n, _) = T.decimal s in n
readByteString :: FilePath -> IO [Int]
readByteString filename = map parse . C.words <$> C.readFile filename
where parse :: C.ByteString -> Int
parse s = let Just (n, _) = C.readInt s in n
main = do
let filename = "../data/data.txt"
defaultMain [
bench "readBaseline" $ nfIO $ readBaseline filename
, bench "readText" $ nfIO $ readText filename
, bench "readByteString" $ nfIO $ readByteString filename
]
import System.Environment
import qualified Data.ByteString.Char8 as C
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
readBaseline :: IO [Int]
readBaseline = map parse . words <$> getLine
where parse :: String -> Int
parse = read
readText :: IO [Int]
readText = map parse . T.words <$> T.getLine
where parse :: T.Text -> Int
parse s = let Right (n, _) = T.decimal s in n
readByteString :: IO [Int]
readByteString = map parse . C.words <$> C.getLine
where parse :: C.ByteString -> Int
parse s = let Just (n, _) = C.readInt s in n
main :: IO ()
main = do
[method] <- getArgs
xs <- case method of
"baseline" -> readBaseline
"text" -> readText
"bytestring" -> readByteString
print $ sum xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment