Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Following the suggestion of acfoltzer (cereal source code), and Daniel Fischer (unsafeCreate), I wrote the code below that works well for my use case, and is fast too:</p> <pre><code>{-#LANGUAGE MagicHash #-} import Data.ByteString (pack, unpack) import Data.ByteString.Internal (unsafeCreate,ByteString) import Data.Bits (shiftR) import GHC.Int (Int64) import GHC.Prim import GHC.Types import GHC.Word import Unsafe.Coerce import Criterion.Main import Foreign -- | Write a Word64 in little endian format putWord64le :: Word64 -&gt; Ptr Word8 -&gt; IO() putWord64le w p = do poke p (fromIntegral (w) :: Word8) poke (p `plusPtr` 1) (fromIntegral (shiftR w 8) :: Word8) poke (p `plusPtr` 2) (fromIntegral (shiftR w 16) :: Word8) poke (p `plusPtr` 3) (fromIntegral (shiftR w 24) :: Word8) poke (p `plusPtr` 4) (fromIntegral (shiftR w 32) :: Word8) poke (p `plusPtr` 5) (fromIntegral (shiftR w 40) :: Word8) poke (p `plusPtr` 6) (fromIntegral (shiftR w 48) :: Word8) poke (p `plusPtr` 7) (fromIntegral (shiftR w 56) :: Word8) {-# INLINE putWord64le #-} encodeDouble :: Double -&gt; ByteString encodeDouble x = unsafeCreate 8 (putWord64le $ unsafeCoerce x) main :: IO () main = defaultMain [ bgroup "encodeDouble" [ bench "78901.234" $ whnf encodeDouble 78901.234 , bench "789.01" $ whnf encodeDouble 789.01 ] ] </code></pre> <p>Criterion output (truncated):</p> <pre><code>estimating cost of a clock call... mean is 46.80361 ns (35 iterations) found 5 outliers among 35 samples (14.3%) 3 (8.6%) high mild 2 (5.7%) high severe benchmarking encodeDouble/78901.234 mean: 18.80689 ns, lb 18.73805 ns, ub 18.97247 ns, ci 0.950 std dev: 516.7499 ps, lb 244.8588 ps, ub 1.043685 ns, ci 0.950 benchmarking encodeDouble/789.01 mean: 18.96963 ns, lb 18.90986 ns, ub 19.06127 ns, ci 0.950 std dev: 374.2191 ps, lb 275.3313 ps, ub 614.4281 ps, ci 0.950 </code></pre> <p>From ~220ns down to ~19ns, nice! I didn't do anything fancy in compilation. Just -O flag will do in GHC7 (Mac, x86_64).</p> <p>Now, trying to figure out how to do it fast with list of doubles!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload