Main.hs (2362B)
1 {-# OPTIONS_GHC -fno-warn-orphans #-} 2 {-# LANGUAGE BangPatterns #-} 3 {-# LANGUAGE DeriveGeneric #-} 4 {-# LANGUAGE DerivingStrategies #-} 5 {-# LANGUAGE NumericUnderscores #-} 6 {-# LANGUAGE OverloadedStrings #-} 7 {-# LANGUAGE StandaloneDeriving #-} 8 9 module Main where 10 11 import Bitcoin.Prim.Script (Term(..), Opcode(..)) 12 import qualified Bitcoin.Prim.Script as S 13 import Control.DeepSeq 14 import Criterion.Main 15 import qualified Data.ByteString as BS 16 import qualified Data.Primitive.ByteArray as BA 17 import GHC.Generics 18 19 deriving stock instance Generic S.Script 20 instance NFData S.Script 21 22 deriving stock instance Generic S.Term 23 instance NFData S.Term 24 25 deriving stock instance Generic S.Opcode 26 instance NFData S.Opcode 27 28 ba_to_bs :: Benchmark 29 ba_to_bs = env setup $ \ba -> 30 bench "ba_to_bs" $ nf S.ba_to_bs ba 31 where 32 setup = do 33 let s = 1024 :: Int 34 ba <- BA.newPinnedByteArray s 35 let go !j 36 | j == s = pure () 37 | otherwise = do 38 BA.writeByteArray ba j (j `rem` 256) 39 go (j + 1) 40 go 0 41 BA.unsafeFreezeByteArray ba 42 43 bs_to_ba :: Benchmark 44 bs_to_ba = bench "bs_to_ba" $ nf S.bs_to_ba (BS.replicate 1024 0x00) 45 46 to_script :: Benchmark 47 to_script = bench "to_script" $ nf S.to_script terms where 48 terms = [ 49 OPCODE OP_DUP,OPCODE OP_HASH160,OPCODE OP_PUSHBYTES_20,BYTE 0x89,BYTE 0xab 50 , BYTE 0xcd,BYTE 0xef,BYTE 0xab,BYTE 0xba,BYTE 0xab,BYTE 0xba,BYTE 0xab 51 , BYTE 0xba,BYTE 0xab,BYTE 0xba,BYTE 0xab,BYTE 0xba,BYTE 0xab,BYTE 0xba 52 , BYTE 0xab,BYTE 0xba,BYTE 0xab,BYTE 0xba,OPCODE OP_EQUALVERIFY 53 , OPCODE OP_CHECKSIG 54 ] 55 56 from_script :: Benchmark 57 from_script = bench "from_script" $ nf S.from_script script where 58 b16 = "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac" 59 script = case S.from_base16 b16 of 60 Nothing -> error "invalid script" 61 Just !s -> s 62 63 to_base16 :: Benchmark 64 to_base16 = bench "to_base16" $ nf S.to_base16 script where 65 b16 = "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac" 66 script = case S.from_base16 b16 of 67 Nothing -> error "invalid script" 68 Just !s -> s 69 70 from_base16 :: Benchmark 71 from_base16 = bench "from_base16" $ nf S.from_base16 b16 where 72 b16 = "76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac" 73 74 main :: IO () 75 main = defaultMain [ 76 ba_to_bs 77 , bs_to_ba 78 , to_script 79 , from_script 80 , to_base16 81 , from_base16 82 ] 83