File: Main.hs

package info (click to toggle)
haskell-cborg-json 0.2.6.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 76 kB
  • sloc: haskell: 188; makefile: 5
file content (67 lines) | stat: -rw-r--r-- 2,272 bytes parent folder | download | duplicates (2)
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
56
57
58
59
60
61
62
63
64
65
66
67
module Main (main) where

import qualified Data.ByteString.Lazy   as LBS
import qualified Codec.Compression.GZip as GZip
import           Control.Monad (unless)
import           System.Directory (doesFileExist)
import           System.Process   (callProcess)

import           Codec.CBOR.JSON (encodeValue, decodeValue)
import           Codec.CBOR.Read (deserialiseFromBytes)
import           Codec.CBOR.Write (toLazyByteString, toStrictByteString)

import           Criterion.Main
                   ( defaultMain, Benchmark, bgroup, bench, env, nf, whnf )
import qualified Data.Aeson as Aeson (Value, decode, encode)


dataFile :: FilePath
dataFile = "bench/data.json.gz"

dataFileURL :: FilePath
dataFileURL = "https://raw.githubusercontent.com/well-typed/cborg/master/cborg-json/bench/data.json.gz"

fetchLargeJSON :: IO ()
fetchLargeJSON = do
    exists <- doesFileExist dataFile
    unless exists $ do
      putStrLn $ "Fetching bechmark data file from " ++ dataFileURL
      callProcess "curl" [dataFileURL, "--output", dataFile]

loadLargeJSONBytes :: IO LBS.ByteString
loadLargeJSONBytes = do
    fetchLargeJSON
    fmap GZip.decompress (LBS.readFile dataFile)

loadLargeJSON :: IO Aeson.Value
loadLargeJSON = do
    bytes <- loadLargeJSONBytes
    let Just json = Aeson.decode bytes
    return json

loadLargeCBORBytes :: IO LBS.ByteString
loadLargeCBORBytes =
    fmap (toLazyByteString . encodeValue) loadLargeJSON

main :: IO ()
main = defaultMain benchmarks

benchmarks :: [Benchmark]
benchmarks =
    [ bgroup "Decode"
        [ env loadLargeJSONBytes $ \largeJSONBytes ->
          bench "JSON" (whnf (Aeson.decode :: LBS.ByteString -> Maybe Aeson.Value) largeJSONBytes)

        , env loadLargeCBORBytes $ \largeCBORBytes ->
          bench "CBOR" (whnf (deserialiseFromBytes (decodeValue False)) largeCBORBytes)

        , env loadLargeCBORBytes $ \largeCBORBytes ->
          bench "CBOR lenient" (whnf (deserialiseFromBytes (decodeValue True)) largeCBORBytes)
        ]
    , env loadLargeJSON $ \largeJSON ->
      bgroup "Encode"
        [ bench "JSON" (nf Aeson.encode largeJSON)
        , bench "CBOR" (nf (toLazyByteString . encodeValue) largeJSON)
        , bench "CBOR strict" (whnf (toStrictByteString . encodeValue) largeJSON)
        ]
    ]