Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sinelaw
Created February 3, 2016 08:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sinelaw/ade2dfc70271db192bbd to your computer and use it in GitHub Desktop.
Save sinelaw/ade2dfc70271db192bbd to your computer and use it in GitHub Desktop.
Binary encode/decode of Fixed
-- run it like:
-- stack ghc --package criterion -- binary.hs -Wall -O2 && ./binary
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import Data.ByteString.Lazy (ByteString)
import Data.Binary
import Data.Fixed
import Criterion.Main
{-# INLINE toPicos #-}
toPicos :: Pico -> Integer
toPicos (MkFixed x) = x
{-# INLINE fromPicos #-}
fromPicos :: Integer -> Pico
fromPicos = MkFixed
instance Binary (Fixed E12) where
get = fromPicos <$> get
put = put . toPicos
main :: IO ()
main = do
let pico = 123 :: Pico
!encodedPico = encode pico
putStrLn $ "Encoded pico " ++ (show pico) ++ ": " ++ show encodedPico
defaultMain
[ bgroup "Pico"
[ bench "encode" $ nf encode pico
, bench "decode" $ nf (decode :: ByteString -> Pico) encodedPico ]
]
-- 700ns for a SINGLE fixed-point value!
--
-- Encoded pico 123.000000000000: "\SOH\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL\ACK\NUL\176N+\222o"
-- benchmarking Pico/encode
-- time 720.4 ns (719.4 ns .. 721.7 ns)
-- 1.000 R² (1.000 R² .. 1.000 R²)
-- mean 719.7 ns (719.0 ns .. 720.6 ns)
-- std dev 2.777 ns (2.380 ns .. 3.290 ns)
-- benchmarking Pico/decode
-- time 745.6 ns (744.9 ns .. 746.3 ns)
-- 1.000 R² (1.000 R² .. 1.000 R²)
-- mean 745.6 ns (744.7 ns .. 746.2 ns)
-- std dev 2.491 ns (1.823 ns .. 4.192 ns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment