File: Sort.hs

package info (click to toggle)
ghc 9.6.6-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 158,216 kB
  • sloc: haskell: 648,228; ansic: 81,656; cpp: 11,808; javascript: 8,444; sh: 5,831; fortran: 3,527; python: 3,277; asm: 2,523; makefile: 2,298; yacc: 1,570; lisp: 532; xml: 196; perl: 145; csh: 2
file content (55 lines) | stat: -rw-r--r-- 1,777 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
-- | This benchmark sorts the lines of a file, like the @sort@ unix utility.
--
-- Tested in this benchmark:
--
-- * Reading the file
--
-- * Splitting into lines
--
-- * Sorting the lines
--
-- * Joining the lines
--
-- * Writing back to a handle
--
{-# LANGUAGE CPP, OverloadedStrings #-}
module Benchmarks.Programs.Sort
    ( benchmark
    ) where

import Test.Tasty.Bench (Benchmark, bgroup, bench, whnfIO)
import System.IO (Handle)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Lazy.IO as TL

benchmark :: FilePath -> Handle -> Benchmark
benchmark i o = bgroup "Sort"
    [ bench "Text" $ whnfIO $ T.readFile i >>= T.hPutStr o . text
    , bench "LazyText" $ whnfIO $ TL.readFile i >>= TL.hPutStr o . lazyText
    , bench "TextByteString" $ whnfIO $ B.readFile i >>=
        B.hPutStr o . T.encodeUtf8 . text . T.decodeUtf8
    , bench "LazyTextByteString" $ whnfIO $ BL.readFile i >>=
        BL.hPutStr o . TL.encodeUtf8 . lazyText .  TL.decodeUtf8
    , bench "TextBuilder" $ whnfIO $ B.readFile i >>=
        BL.hPutStr o . TL.encodeUtf8 . textBuilder . T.decodeUtf8
    ]

text :: T.Text -> T.Text
text = T.unlines . L.sort . T.lines

lazyText :: TL.Text -> TL.Text
lazyText = TL.unlines . L.sort . TL.lines

-- | Text variant using a builder monoid for the final concatenation
--
textBuilder :: T.Text -> TL.Text
textBuilder = TLB.toLazyText . mconcat . L.intersperse (TLB.singleton '\n') .
    map TLB.fromText . L.sort . T.lines