|
| 1 | +module BasicLibraries.ChapterExercises.QueueBenchmark ( |
| 2 | + benchmarks |
| 3 | +) where |
| 4 | + |
| 5 | +import Criterion |
| 6 | +import Data.Sequence |
| 7 | +import BasicLibraries.ChapterExercises.Queue |
| 8 | + |
| 9 | +listQueueBench :: Int -> [Int] |
| 10 | +listQueueBench n = foldr go [] [1..2*n] |
| 11 | + where go x acc |
| 12 | + | even x = x : acc |
| 13 | + | otherwise = init acc |
| 14 | + |
| 15 | +queueBench :: Int -> Queue Int |
| 16 | +queueBench n = foldr go initQueue [1..2*n] |
| 17 | + where initQueue = Queue [] [] |
| 18 | + go x acc |
| 19 | + | even x = push x acc |
| 20 | + | otherwise = let Just (_, acc') = pop acc in acc' |
| 21 | + |
| 22 | +sequenceBench :: Int -> Seq Int |
| 23 | +sequenceBench n = foldr go empty [1..2*n] |
| 24 | + where go x acc |
| 25 | + | even x = x <| acc |
| 26 | + | otherwise = let acc' :> _ = viewr acc in acc' |
| 27 | + |
| 28 | +benchmarks :: [Benchmark] |
| 29 | +benchmarks = |
| 30 | + [ bench "list queue" $ nf listQueueBench 123456 |
| 31 | + , bench "queue" $ whnf queueBench 123456 |
| 32 | + , bench "sequence" $ whnf sequenceBench 123456 |
| 33 | + ] |
| 34 | + |
| 35 | +{- Reference benchmark results |
| 36 | +
|
| 37 | +benchmarking Queue/list queue |
| 38 | +time 27.27 ms (26.40 ms .. 27.86 ms) |
| 39 | + 0.996 R² (0.991 R² .. 0.999 R²) |
| 40 | +mean 27.70 ms (27.21 ms .. 28.66 ms) |
| 41 | +std dev 1.439 ms (768.4 μs .. 2.317 ms) |
| 42 | +variance introduced by outliers: 16% (moderately inflated) |
| 43 | +
|
| 44 | +benchmarking Queue/queue |
| 45 | +time 10.75 ms (10.51 ms .. 11.01 ms) |
| 46 | + 0.996 R² (0.993 R² .. 0.998 R²) |
| 47 | +mean 10.98 ms (10.83 ms .. 11.27 ms) |
| 48 | +std dev 545.3 μs (329.6 μs .. 914.8 μs) |
| 49 | +variance introduced by outliers: 23% (moderately inflated) |
| 50 | +
|
| 51 | +benchmarking Queue/sequence |
| 52 | +time 7.768 ms (7.597 ms .. 7.926 ms) |
| 53 | + 0.996 R² (0.993 R² .. 0.999 R²) |
| 54 | +mean 8.119 ms (7.932 ms .. 8.509 ms) |
| 55 | +std dev 719.3 μs (393.4 μs .. 1.096 ms) |
| 56 | +variance introduced by outliers: 51% (severely inflated) |
| 57 | +
|
| 58 | +-} |
0 commit comments