|
| 1 | +{-# LANGUAGE BangPatterns #-} |
| 2 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 3 | +{-# LANGUAGE TypeApplications #-} |
| 4 | +{- | |
| 5 | +Here we test that GHC is able to optimize well construction of vector |
| 6 | +using monadic\/applicative actions. Well is understood as able to |
| 7 | +generate code which does not allocate except for buffer and some |
| 8 | +constant overhead. |
| 9 | +-} |
| 10 | +module Inspect.Alloc where |
| 11 | + |
| 12 | +import Data.Int |
| 13 | +-- import Data.Monoid |
| 14 | +import Data.Functor.Identity |
| 15 | +import Test.Tasty |
| 16 | +import Test.Tasty.HUnit |
| 17 | +import System.Mem |
| 18 | +import Test.Alloc |
| 19 | + |
| 20 | +import qualified Data.Vector.Unboxed as VU |
| 21 | + |
| 22 | + |
| 23 | +tests :: TestTree |
| 24 | +tests = testGroup "allocations" |
| 25 | + [ testGroup "traversable" |
| 26 | + [ testCase "IO" |
| 27 | + $ checkAllocations (linear 8) |
| 28 | + $ whnfIO (VU.traverse (\_ -> getAllocationCounter) vector) |
| 29 | + , testCase "Identity" |
| 30 | + $ checkAllocations (linear 8) |
| 31 | + $ VU.traverse (\n -> Identity (10*n)) `whnf` vector |
| 32 | + -- NOTE: Naive traversal is lazy and allocated 2 words per element |
| 33 | + -- |
| 34 | + -- , testCase "Const Sum" |
| 35 | + -- $ checkAllocations constant |
| 36 | + -- $ whnf (VU.traverse (Const @_ @() . Sum)) vector |
| 37 | + ] |
| 38 | + , testGroup "unstreamM" |
| 39 | + [ testCase "IO" |
| 40 | + $ checkAllocations (linear 8) |
| 41 | + $ whnfIO (VU.replicateM size getAllocationCounter) |
| 42 | + -- , testCase "Identity" |
| 43 | + -- $ checkAllocations (linear 8) |
| 44 | + -- $ (\sz -> VU.generateM sz (\n -> Identity (fromIntegral n :: Int64))) `whnf` size |
| 45 | + ] |
| 46 | + ] |
| 47 | + |
| 48 | + |
| 49 | +-- | Constant overhead. Measurement precision is 4k |
| 50 | +overhead :: Int64 |
| 51 | +overhead = 4096*2 |
| 52 | + |
| 53 | +-- | Vector size. It should be large so 1byte per element will be |
| 54 | +-- large than page. |
| 55 | +size :: Int |
| 56 | +size = 100000 |
| 57 | + |
| 58 | +vector :: VU.Vector Int64 |
| 59 | +{-# NOINLINE vector #-} |
| 60 | +vector = VU.generate size fromIntegral |
| 61 | + |
| 62 | +-- | N bytes per element + constant overhead. We also check that bound |
| 63 | +-- is tight. |
| 64 | +linear :: Int -> Range |
| 65 | +linear n = Range |
| 66 | + { allocHi = fromIntegral (n * size) + overhead |
| 67 | + , allocLo = fromIntegral ((n-1) * size) + overhead |
| 68 | + } |
| 69 | + |
| 70 | +-- | Only constant overhead |
| 71 | +constant :: Range |
| 72 | +constant = Range { allocHi = overhead |
| 73 | + , allocLo = 0 |
| 74 | + } |
0 commit comments