### Basic Criterion Benchmark Setup Source: https://github.com/haskell/criterion/blob/master/_autodocs/configuration.md A simple example demonstrating how to set up and run a basic benchmark using Criterion's default configuration. ```haskell import Criterion.Main main = defaultMain [ bench "fib 30" $ whnf fib 30 ] ``` -------------------------------- ### Benchmark Environment Setup and Cleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Use `env` for shared setup, `envWithCleanup` for setup with explicit cleanup, and `perRunEnv` for setup per iteration. ```haskell -- Shared setup, once per benchmark group import qualified Data.Vector as V main = defaultMain [ env (V.replicate 10000 0) $ \vec -> bench "read" $ nfIO (evaluate (V.sum vec)) ] ``` ```haskell -- Explicit cleanup import System.IO main = defaultMain [ envWithCleanup (openFile "input.txt" ReadMode) hClose $ \handle -> bench "read" $ nfIO (hGetContents handle) ] ``` ```haskell -- Fresh environment per iteration (slowest) main = defaultMain [ perRunEnv (return 42) $ \x -> bench "add" $ nf (+x) 10 ] ``` -------------------------------- ### Environment Setup: Once per Run Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Use `perRunEnv` for setup that needs to be isolated to a single run of a benchmark. This ensures the most isolated measurements, useful for timing-sensitive operations. ```haskell main = defaultMain [ perRunEnv (getCurrentTime) $ \t -> bench "diff" $ nf (\t0 -> diffUTCTime t t0) t ] ``` -------------------------------- ### Benchmark with Environment Setup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Use `env` to create a benchmark that requires setup and cleanup of resources. The environment is created once per benchmark group and shared across all benchmarks using it. ```haskell env :: IO a -> (a -> Benchmark) -> Benchmark ``` ```haskell import qualified Data.Vector as V main = defaultMain [ env (V.replicateM 10000 newRef) $ \refs -> bench "read ref" $ nfIO (readIORef (V.head refs)) ] ``` -------------------------------- ### Chart Initialization Lifecycle Source: https://github.com/haskell/criterion/blob/master/www/report.html Handles the initial setup of a chart instance, including retina scaling, event binding, responsive resizing, and tooltip setup. Notifies plugins before and after initialization. ```javascript initialize: function() { var t = this; Le.notify(t, "beforeInit"); H.retinaScale(t, t.options.devicePixelRatio); t.bindEvents(); t.options.responsive && t.resize(!0); t.initToolTip(); Le.notify(t, "afterInit"); return t; } ``` -------------------------------- ### Install Criterion with Cabal Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Use this command to install the Criterion library if it's not found during compilation. ```bash cabal update cabal install criterion ``` -------------------------------- ### Criterion Command Line Output Example Source: https://github.com/haskell/criterion/blob/master/README.markdown This is an example of the output Criterion prints to the terminal window after running benchmarks. It displays key performance metrics and their estimated bounds. ```text benchmarking ByteString/HashMap/random time 4.046 ms (4.020 ms .. 4.072 ms) 1.000 R² (1.000 R² .. 1.000 R²) mean 4.017 ms (4.010 ms .. 4.027 ms) std dev 27.12 μs (20.45 μs .. 38.17 μs) ``` -------------------------------- ### Criterion Command-Line Usage Examples Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Demonstrates various command-line options for listing, running, and configuring benchmarks. ```bash # List benchmarks cabal run -- --list ``` ```bash # Run with default settings cabal run ``` ```bash # Run matching pattern cabal run -- fib # prefix match cabal run -- -m glob "*/map*" # glob match cabal run -- -m pattern "sort" # substring match cabal run -- -m ipattern "SORT" # case-insensitive ``` ```bash # Generate report cabal run -- -o report.html ``` ```bash # Run with higher precision cabal run -- --resamples 5000 -I 0.99 ``` ```bash # Verbose output cabal run -- -v 2 ``` ```bash # Fixed iterations (no analysis) cabal run -- -n 1000 ``` -------------------------------- ### Benchmark with Per-Batch Environment and Cleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Use `perBatchEnvWithCleanup` for benchmarks requiring per-batch environment setup with explicit cleanup. It allows for controlled setup and teardown of resources for each benchmark run. ```haskell perBatchEnvWithCleanup :: IO a -> (a -> IO ()) -> (a -> Benchmark) -> Benchmark ``` -------------------------------- ### Environment Setup: Once per Batch Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Use `perBatchEnv` to set up an environment that is fresh for each batch of benchmark iterations. This is useful for resources that should be reset between batches. ```haskell main = defaultMain [ perBatchEnv (newIORef 0) $ \ref -> bench "increment" $ nfIO (modifyIORef ref (+1) >> readIORef ref) ] ``` -------------------------------- ### perBatchEnvWithCleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Provides per-batch environment setup with explicit cleanup. ```APIDOC ## perBatchEnvWithCleanup ### Description Provides per-batch environment setup with explicit cleanup. ### Signature ```haskell perBatchEnvWithCleanup :: IO a -> (a -> IO ()) -> (a -> Benchmark) -> Benchmark ``` ### Parameters #### Path Parameters - **setup** (IO a) - Required - Create environment - **cleanup** (a -> IO ()) - Required - Clean up - **mkBench** (a -> Benchmark) - Required - Create benchmark ### Return Benchmark with per-batch environment and cleanup. ### Source Criterion.Types via re-export ``` -------------------------------- ### Environment Setup: Once per Benchmark Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Use `perBatchEnv` to set up a fresh resource for each individual benchmark within a group. The resource is cleaned up after each benchmark runs. ```haskell perBatchEnv (createExpensive) $ \resource -> bgroup "tests" [ bench "a" $ nfIO (use resource), -- fresh resource bench "b" $ nfIO (use resource) -- fresh resource ] ``` -------------------------------- ### Environment Setup: Once per Group Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Use `env` to set up a resource once before all benchmarks in a group and clean it up afterwards. This is suitable for resources that can be shared across multiple benchmarks. ```haskell env (createExpensive) $ \resource -> bgroup "tests" [ bench "a" $ nfIO (use resource), -- shares resource bench "b" $ nfIO (use resource) -- shares resource ] ``` -------------------------------- ### Basic Cabal Setup for Criterion Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Configure your `criterion.cabal` file to include Criterion as a build dependency and set GHC options for optimization and threading. ```cabal executable mybench main-is: Main.hs build-depends: base, criterion ghc-options: -O2 -threaded ``` -------------------------------- ### Custom Benchmark Configuration with defaultMainWith Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Shows how to customize benchmark execution using `defaultMainWith`. This example sets a specific time limit for the benchmarks. ```haskell import Criterion.Main.Options main = defaultMainWith config benchmarks where config = defaultConfig { timeLimit = 10 } ``` -------------------------------- ### env Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Creates a benchmark that requires setup and cleanup of resources. The environment is created once per benchmark group and shared across all benchmarks that use it. ```APIDOC ## env ### Description Creates a benchmark that requires setup and cleanup of resources. The environment is created once per benchmark group and shared across all benchmarks that use it. ### Signature ```haskell env :: IO a -> (a -> Benchmark) -> Benchmark ``` ### Parameters #### Path Parameters - **setup** (IO a) - Required - IO action to create the environment - **mkBench** (a -> Benchmark) - Required - Function to create benchmark(s) using the environment ### Return A Benchmark that will set up the environment before running. ### Cleanup Cleanup is performed automatically after all benchmarks using this environment complete. ### Example ```haskell import qualified Data.Vector as V main = defaultMain [ env (V.replicateM 10000 newRef) $ \refs -> bench "read ref" $ nfIO (readIORef (V.head refs)) ] ``` ``` -------------------------------- ### Minimal Haskell Benchmark Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md A basic example demonstrating how to define a recursive function and benchmark its performance for different inputs using `defaultMain` and `whnf`. ```haskell import Criterion.Main fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) main = defaultMain [ bgroup "fib" [ bench "10" $ whnf fib 10, bench "20" $ whnf fib 20, bench "30" $ whnf fib 30 ] ] ``` -------------------------------- ### Batch Processing Benchmarks with runMode Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Provides an example of using `runMode` for batch processing of benchmarks. This is useful for automated testing or CI environments. ```haskell import Criterion.Main let mode = Run defaultConfig Prefix ["fib"] runMode mode [bench "fib" $ whnf fib 30] ``` -------------------------------- ### Get Radar Chart Index Angle Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates the angle in radians for a given data index on a radar chart, considering the start angle option. ```javascript getIndexAngle:function(t){var e=this.chart,n=(t*(360/e.data.labels.length)+((e.options||{}).startAngle||0))%360;return(n<0?n+360:n)*Math.PI*2/360} ``` -------------------------------- ### Get Fill Points Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Retrieves the points for filling an area in a chart. This function handles different fill modes ('start', 'end', 'origin') and scale types to calculate the correct coordinates. ```javascript function vi(t) { return (t.el._scale || {}).getPointPositionForValue ? function(t) { var e, n, i, a, r, o = t.el._scale, s = o.options, l = o.chart.data.labels.length, u = t.fill, d = []; if (!l) return null; for (e = s.ticks.reverse ? o.max : o.min, n = s.ticks.reverse ? o.min : o.max, i = o.getPointPositionForValue(0, e), a = 0; a < l; ++a) r = "start" === u || "end" === u ? o.getPointPositionForValue(a, "start" === u ? e : n) : o.getBasePosition(a), s.gridLines.circular && (r.cx = i.x, r.cy = i.y, r.angle = o.getIndexAngle(a) - Math.PI / 2), d.push(r); return d }(t) : function(t) { var e, n = t.el._model || {}, i = t.el._scale || {}, a = t.fill, r = null; if (isFinite(a)) return null; if ("start" === a ? r = void 0 === n.scaleBottom ? i.bottom : n.scaleBottom : "end" === a ? r = void 0 === n.scaleTop ? i.top : n.scaleTop : void 0 !== n.scaleZero ? r = n.scaleZero : i.getBasePixel && (r = i.getBasePixel()), null != r) { if (void 0 !== r.x && void 0 !== r.y) return r; if (H.isFinite(r)) return { x: (e = i.isHorizontal()) ? r : null, y: e ? null : r } } return null }(t) } ``` -------------------------------- ### Simple Benchmarking with defaultMain Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Illustrates the simplest way to set up a benchmark using `defaultMain`. This is suitable for straightforward benchmarking tasks. ```haskell main = defaultMain [ bench "operation" $ whnf function input ] ``` -------------------------------- ### Custom Criterion Configuration Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Example of how to customize Criterion's default configuration options such as time limit, resamples, and output files. ```haskell import Criterion.Main.Options config = defaultConfig { timeLimit = 30, resamples = 5000, reportFile = Just "results/report.html", csvFile = Just "results/summary.csv", verbosity = Verbose } ``` -------------------------------- ### Get Radar Chart Base Position Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Calculates the starting position for drawing on the radar chart, typically corresponding to the zero value or the minimum data value. This is used for drawing axes or baseline elements. ```javascript function(t){var e=this.min,n=this.max;return this.getPointPositionForValue(t||0,this.beginAtZero?0:e<0&&n<0?n:e>0&&n>0?e:0)} ``` -------------------------------- ### Establishing and Comparing Benchmark Baselines Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Outlines the process for setting up an initial benchmark baseline and then running a new comparison after optimizations. It involves generating HTML and CSV reports for both runs and comparing them visually or via diffing. ```bash # First run - establish baseline cabal run -- --output baseline.html --csv baseline.csv # Later - after optimization cabal run -- --output current.html --csv current.csv # Compare: open both HTML files in browser, compare charts # Or: diff CSV files in spreadsheet ``` -------------------------------- ### Get Constraint Height Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets the constrained height of an element, considering CSS properties like 'max-height'. ```javascript H.getConstraintHeight=function(t){return n(t,"max-height","clientHeight")} ``` -------------------------------- ### Get Constraint Width Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets the constrained width of an element, considering CSS properties like 'max-width'. ```javascript H.getConstraintWidth=function(t){return n(t,"max-width","clientWidth")} ``` -------------------------------- ### Getting Scale Defaults Source: https://github.com/haskell/criterion/blob/master/www/report.html Use `getScaleDefaults` to get the default configuration options for a specific scale type. ```javascript Re.getScaleDefaults('linear'); ``` -------------------------------- ### Criterion CLI Help and Basic Commands Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Use these commands to get help, list benchmarks, check the version, or set basic run parameters like time limits. ```bash benchmark --help # Show help ``` ```bash benchmark --list # List benchmarks ``` ```bash benchmark --version # Show version ``` ```bash benchmark -L 10 # Set time limit to 10s ``` -------------------------------- ### Get Parent Node Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets the parent node of an element, handling shadow DOM by returning the host element if the parent is a shadow root. ```javascript H._getParentNode=function(t){var e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e} ``` -------------------------------- ### Get Sorted Visible Dataset Metas in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html A convenience method to get only the visible dataset meta objects, sorted by their order or index. ```javascript _getSortedVisibleDatasetMetas:function(){return this._getSortedDatasetMetas(!0)}, ``` -------------------------------- ### Get Dataset at Event in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets the dataset that intersects with the event coordinates, using the 'dataset' mode. Useful for identifying which dataset an event occurred on. ```javascript getDatasetAtEvent:function(t){return re.modes.dataset(this,t,{intersect:!0})}, ``` -------------------------------- ### defaultMainWith Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Entry point for a benchmark program with custom configuration. It parses command-line arguments and applies them on top of a provided default configuration. ```APIDOC ## defaultMainWith ### Description Entry point for a benchmark program with custom configuration. Parses command-line arguments and applies them on top of the provided default configuration. ### Method `defaultMainWith :: Config -> [Benchmark] -> IO () ### Parameters #### Path Parameters - **config** (Config) - Required - Default configuration to use as baseline - **benchmarks** ([Benchmark]) - Required - List of benchmarks to execute ### Response Returns IO () which runs the configured benchmarks. ### Throws - ExitFailure if command-line parsing fails ### Example ```haskell import Criterion.Main import Criterion.Main.Options myConfig = defaultConfig { resamples = 500, -- fewer resamples for faster turnaround timeLimit = 10 -- allow more time per benchmark } main = defaultMainWith myConfig [ bench "expensive" $ nf complexFunction input ] ``` ``` -------------------------------- ### Interpreting Mean and Confidence Interval Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md This example shows how to interpret the mean and confidence interval of a benchmark result. A narrow CI indicates a precise measurement. ```text benchmarking fib/30 mean 129.8 ms (129.1 ms .. 130.6 ms) ``` -------------------------------- ### Get Element at Event in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets the single element at the event coordinates using the 'single' mode. Useful for identifying a specific data point. ```javascript getElementAtEvent:function(t){return re.modes.single(this,t)}, ``` -------------------------------- ### List all available benchmarks Source: https://github.com/haskell/criterion/blob/master/README.markdown Use the --list option to display all benchmark names if you have forgotten them. ```shell --list ``` -------------------------------- ### Environment Setup: Once per Iteration Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Use `perRunEnv` for the highest level of isolation, setting up a fresh resource for every single iteration of a benchmark. This is the slowest but provides the most isolated environment. ```haskell perRunEnv (createExpensive) $ \resource -> bench "test" $ nfIO (use resource) -- fresh per iteration ``` -------------------------------- ### Get Radar Chart Point Position for Value Source: https://github.com/haskell/criterion/blob/master/www/report.html Combines distance calculation and angle calculation to get the exact (x, y) position for a data value on the radar chart. ```javascript getPointPositionForValue:function(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))} ``` -------------------------------- ### perRunEnvWithCleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Sets up and tears down an environment for each benchmark run. This is useful for managing resources that need to be initialized before each benchmark and cleaned up afterward. ```APIDOC ## perRunEnvWithCleanup ### Description Per-run environment with explicit cleanup. This function allows you to define a setup action to create an environment, a cleanup action to release it, and a function to create a benchmark that uses this environment. ### Method N/A (Haskell function) ### Signature perRunEnvWithCleanup :: IO a -> (a -> IO ()) -> (a -> Benchmark) -> Benchmark ### Parameters #### Function Parameters - **setup** (IO a) - Yes - Action to create the environment. - **cleanup** (a -> IO ()) - Yes - Action to clean up the environment. - **mkBench** (a -> Benchmark) - Yes - Function to create a benchmark using the environment. ``` -------------------------------- ### Get Elements at Event for Mode in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html A general method to get elements at event coordinates for a specified mode. Returns an empty array if the mode is not found or not a function. ```javascript getElementsAtEventForMode:function(t,e,n){var i=re.modes\[e\];return"function"==typeof i?i(this,t,n):\[\]}, ``` -------------------------------- ### Get Elements at Event in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets all elements at the event coordinates that intersect with the event, using the 'label' mode. Useful for identifying multiple data points in a series. ```javascript getElementsAtEvent:function(t){return re.modes.label(this,t,{intersect:!0})}, ``` -------------------------------- ### Benchmarking IO with whnfIO (Potential Issue) Source: https://github.com/haskell/criterion/blob/master/README.markdown Demonstrates benchmarking an IO action using `whnfIO`. This can lead to resource exhaustion if the IO action involves lazy I/O, as the file handle may not be closed. ```haskell import Criterion.Main main = defaultMain [ bench "whnfIO readFile" $ whnfIO (readFile "BadReadFile.hs") ] ``` -------------------------------- ### Benchmark with Explicit Environment Cleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Use `envWithCleanup` for benchmarks with explicit resource cleanup, offering more control than `env`. It takes setup IO action, a cleanup IO action, and a function to create benchmarks from the environment. ```haskell envWithCleanup :: IO a -> (a -> IO ()) -> (a -> Benchmark) -> Benchmark ``` ```haskell main = defaultMain [ envWithCleanup (openFile "test.txt" ReadMode) hClose $ \handle -> bench "read file" $ nfIO (readFile "test.txt") ] ``` -------------------------------- ### Interactive Benchmarking with benchmark Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Demonstrates how to use the `benchmark` function for interactive benchmarking within GHCi. Requires setting the prompt for clarity. ```haskell import Criterion :set prompt "ghci> " benchmark (whnf fib 30) ``` -------------------------------- ### Helper Function to Get Computed Style Source: https://github.com/haskell/criterion/blob/master/www/report.html A utility function to get the computed style of an element or its parent node. It handles cases where styles might be inherited or directly applied. ```javascript function t(t,e,n){var i;return"string"==typeof t?(i=parseInt(t,10),-1!==t.indexOf("%"&&(i=i/100*e.parentNode[n])):i=t,i}function e(t){return null!=t&&"none"!==t}function n(n,i,a){var r=document.defaultView,o=H._getParentNode(n),s=r.getComputedStyle(n)[i],l=r.getComputedStyle(o)[i],u=e(s),d=e(l),h=Number.POSITIVE_INFINITY;return u||d?Math.min(u?t(s,n,a):h,d?t(l,o,a):h):"none"}H.where=fun ``` -------------------------------- ### Get Elements at X-Axis in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html Gets all elements that intersect with the event on the x-axis, using the 'x-axis' mode. Useful for highlighting data points along a specific vertical line. ```javascript getElementsAtXAxis:function(t){return re.modes.x-axis(this,t,{intersect:!0})}, ``` -------------------------------- ### Running Criterion Benchmark from Command Line Source: https://github.com/haskell/criterion/blob/master/README.markdown Example of how to run a Criterion benchmark program using cabal. The --output flag can be used to generate an HTML report. ```shell $ cabal run Fibber.hs ``` ```shell $ cabal run Fibber.hs -- --output fibber.html ``` -------------------------------- ### Specify benchmarks to run Source: https://github.com/haskell/criterion/blob/master/README.markdown Run specific benchmarks by enumerating their names. Names are treated as prefixes by default. ```shell $ ./Fibber 'fib/fib 1' ``` -------------------------------- ### Get Sorted Visible Dataset Metas Source: https://github.com/haskell/criterion/blob/master/www/fibber.html A convenience method to get only the visible dataset metadata, sorted by 'order' and 'index'. Use when you only need to process or draw visible datasets. ```javascript _getSortedVisibleDatasetMetas:function(){return this._getSortedDatasetMetas(!0)} ``` -------------------------------- ### Get Radar Chart Point Position for Value Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Combines `getIndexAngle` and `getDistanceFromCenterForValue` to get the precise (x, y) coordinates for a data value at a specific index. Useful for plotting data points. ```javascript function(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))} ``` -------------------------------- ### Sine Easing Functions (In, Out, InOut) Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Sine easing functions create smooth, natural-looking animations that resemble a sine wave. 'easeInSine' starts slowly and accelerates, 'easeOutSine' starts fast and decelerates, and 'easeInOutSine' provides a gentle S-curve. ```javascript easeInSine:function(t){return 1-Math.cos(t*(Math.PI/2))} ``` ```javascript easeOutSine:function(t){return Math.sin(t*(Math.PI/2))} ``` ```javascript easeInOutSine:function(t){return-.5*(Math.cos(Math.PI*t)-1)} ``` -------------------------------- ### List Benchmarks Source: https://github.com/haskell/criterion/blob/master/_autodocs/configuration.md Use the --list option to display all available benchmarks without executing them. ```bash cabal run mybench -- --list ``` -------------------------------- ### Get Label for Index in Category Scale in Criterion.js Source: https://github.com/haskell/criterion/blob/master/www/report.html Retrieves the label string for a given data index and dataset. It checks if the scale is the value scale for the dataset; if so, it gets the value from the dataset. Otherwise, it returns the label from the category scale's labels. ```javascript var t=this.chart;return n.chart.getDatasetMeta(e).controller._getValueScaleId()===this.id?this.getRightValue(n.data.datasets[e].data[t]):this._getLabels()[t] ``` -------------------------------- ### Running Criterion Benchmarks via Cabal Source: https://github.com/haskell/criterion/blob/master/_autodocs/README.md Demonstrates common command-line invocations for running Criterion benchmarks using Cabal. Includes options for generating HTML reports and listing benchmarks. ```bash cabal run ``` ```bash cabal run -- --output report.html ``` ```bash cabal run -- --list ``` ```bash cabal run -- fib ``` ```bash cabal run -- -m pattern sort ``` -------------------------------- ### Circular Easing Functions (In, Out, InOut) Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Circular easing functions create animations that accelerate or decelerate using a circular curve. 'easeInCirc' starts slowly and accelerates, 'easeOutCirc' starts fast and decelerates, and 'easeInOutCirc' provides a smooth transition with a circular path. ```javascript easeInCirc:function(t){return t>=1?t:-(Math.sqrt(1-t*t)-1)} ``` ```javascript easeOutCirc:function(t){return Math.sqrt(1-(t-=1)*t)} ``` ```javascript easeInOutCirc:function(t){return(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)} ``` -------------------------------- ### perBatchEnv Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Sets up the environment once per benchmark run (all iterations of one benchmark), not per benchmark group. ```APIDOC ## perBatchEnv ### Description Sets up the environment once per benchmark run (all iterations of one benchmark), not per benchmark group. ### Signature ```haskell perBatchEnv :: IO a -> (a -> Benchmark) -> Benchmark ``` ### Parameters #### Path Parameters - **setup** (IO a) - Required - Create environment - **mkBench** (a -> Benchmark) - Required - Create benchmark from environment ### Return A Benchmark with per-batch environment setup. ### Use when You need fresh state for each benchmark but want to share across iterations of the same benchmark. ### Source Criterion.Types via re-export ``` -------------------------------- ### Exponential Easing Functions (In, Out, InOut) Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Exponential easing functions create animations that accelerate or decelerate very rapidly. 'easeInExpo' starts very slow and accelerates quickly, 'easeOutExpo' starts fast and decelerates quickly, and 'easeInOutExpo' provides a smooth transition with rapid change in the middle. ```javascript easeInExpo:function(t){return 0===t?0:Math.pow(2,10*(t-1))} ``` ```javascript easeOutExpo:function(t){return 1===t?1:1-Math.pow(2,-10*t)} ``` ```javascript easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(2-Math.pow(2,-10*--t))} ``` -------------------------------- ### Create a Benchmark File Source: https://github.com/haskell/criterion/blob/master/_autodocs/START_HERE.md Defines a basic benchmark suite for Fibonacci numbers using Criterion. Requires importing Criterion.Main. ```haskell import Criterion.Main main = defaultMain [ bgroup "fib" [ bench "10" $ whnf fib 10, bench "20" $ whnf fib 20 ] ] fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) ``` -------------------------------- ### Customizing Benchmark Time Limit Source: https://github.com/haskell/criterion/blob/master/_autodocs/configuration.md Shows how to create a custom configuration with an extended time limit for benchmarks. Import Criterion.Main.Options for custom configurations. ```haskell import Criterion.Main import Criterion.Main.Options myConfig = defaultConfig { timeLimit = 10 -- Allow 10 seconds per benchmark } main = defaultMainWith myConfig [ bench "slow operation" $ nf slowFunc largeInput ] ``` -------------------------------- ### Get Angle and Distance from Point Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates the angle and distance between two points. ```javascript H.getAngleFromPoint=function(t,e){var n=e.x-t.x,i=e.y-t.y,a=Math.sqrt(n*n+i*i),r=Math.atan2(i,n);return r<-.5*Math.PI&&(r+=2*Math.PI),{angle:r,distance:a}} ``` -------------------------------- ### Create Cabal Project and Add Criterion Source: https://github.com/haskell/criterion/blob/master/_autodocs/quick-start.md Initialize a new Haskell library project using `cabal init` and then add Criterion to the `build-depends` section in your `.cabal` file. ```bash cabal init --lib --language Haskell2010 # Then add criterion to build-depends ``` -------------------------------- ### Get Fill Target Source: https://github.com/haskell/criterion/blob/master/www/report.html Determines the fill target for a dataset based on its configuration and visibility. ```javascript function mi(t,e,n){var i,a=t._model||{},r=a.fill;if(void 0===r&&(r=!!a.backgroundColor),!1===r||null===r)return!1;if(!0===r)return"origin";if(i=parseFloat(r,10),isFinite(i)&&Math.floor(i)===i)return"-"!==r[0]&&"+"!==r[0]||(i=e+i),!(i===e||i<0||i>=n)&&i;switch(r){case"bottom":return"start";case"top":return"end";case"zero":return"origin";case"origin":case"start":case"end":return r;default:return!1}} ``` -------------------------------- ### Getting Plugin Count Source: https://github.com/haskell/criterion/blob/master/www/report.html The `count` method returns the number of currently registered plugins. ```javascript Le.count(); ``` -------------------------------- ### envWithCleanup Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Creates a benchmark with explicit resource cleanup, offering more control than `env`. ```APIDOC ## envWithCleanup ### Description Creates a benchmark with explicit resource cleanup, offering more control than `env`. ### Signature ```haskell envWithCleanup :: IO a -> (a -> IO ()) -> (a -> Benchmark) -> Benchmark ``` ### Parameters #### Path Parameters - **setup** (IO a) - Required - Create the environment - **cleanup** (a -> IO ()) - Required - Clean up the environment - **mkBench** (a -> Benchmark) - Required - Create benchmarks from environment ### Return A Benchmark with explicit cleanup semantics. ### Example ```haskell main = defaultMain [ envWithCleanup (openFile "test.txt" ReadMode) hClose $ \handle -> bench "read file" $ nfIO (readFile "test.txt") ] ``` ``` -------------------------------- ### Getting Scale Constructor Source: https://github.com/haskell/criterion/blob/master/www/report.html Use `getScaleConstructor` to retrieve the constructor function for a registered scale type. ```javascript Re.getScaleConstructor('category'); ``` -------------------------------- ### CI/CD Integration Configuration Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Use this configuration for running benchmarks in an automated pipeline. It balances speed and accuracy with minimal output. ```haskell config = defaultConfig { timeLimit = 5, resamples = 1000, junitFile = Just "results.xml", verbosity = Quiet } ``` -------------------------------- ### Getting All Registered Plugins Source: https://github.com/haskell/criterion/blob/master/www/report.html The `getAll` method returns an array of all currently registered plugin instances. ```javascript Le.getAll(); ``` -------------------------------- ### Get Visible Dataset Weight Total Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates the total weight of all visible datasets in the chart. ```javascript _getVisibleDatasetWeightTotal:function(){return this._getRingWeightOffset(this.chart.data.datasets.length)} ``` -------------------------------- ### Criterion.Main.Options Source: https://github.com/haskell/criterion/blob/master/_autodocs/module-index.md Provides functions for command-line parsing and default configuration settings for Criterion benchmarks. ```APIDOC ## Module Criterion.Main.Options ### Description Provides functions for command-line parsing and default configuration settings for Criterion benchmarks. Useful when building custom benchmark programs or accessing default configurations. ### Exported Types - `Mode` - `MatchType` ### Exported Constants - `defaultConfig` ### Exported Functions - `parseWith` - `config` - `describe` - `describeWith` - `versionInfo` ### Example Usage ```haskell import Criterion.Main.Options myConfig = defaultConfig { timeLimit = 10 } ``` ``` -------------------------------- ### Get Element Style Source: https://github.com/haskell/criterion/blob/master/www/report.html Retrieves the style options for a specific data element based on its index. ```javascript getStyle:function(t){ var e,n=this.getMeta(),i=n.dataset; return this._c ``` -------------------------------- ### Getting Dataset Style Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Retrieves the style properties for a dataset element. This is a placeholder and needs implementation. ```javascript getStyle:function(t){var e,n=this.getMeta(),i=n.dataset;return this._c ``` -------------------------------- ### defaultMain Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md The main entry point for a benchmark program. It parses command-line arguments and runs benchmarks with default configuration settings. ```APIDOC ## defaultMain ### Description The main entry point for a benchmark program. Parses command-line arguments and runs benchmarks with default configuration (95% confidence interval, 5 second time limit, 1000 bootstrap resamples). ### Method `defaultMain :: [Benchmark] -> IO () ### Parameters #### Path Parameters - **benchmarks** ([Benchmark]) - Required - List of benchmark specifications to execute ### Response Returns IO () which executes the benchmarks. ### Throws - ExitFailure if command-line parsing fails ### Example ```haskell import Criterion.Main fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) main = defaultMain [ bgroup "fib" [ bench "1" $ whnf fib 1 , bench "5" $ whnf fib 5 , bench "10" $ whnf fib 10 ] ] ``` ``` -------------------------------- ### Organize Benchmarks by Feature Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Structure your benchmarks into groups based on features or modules for better readability. Use `defaultMain` to run the benchmark suite. ```haskell main = defaultMain -- Organize by feature/module [ bgroup "list operations" listBenches , bgroup "string operations" stringBenches , bgroup "data structures" structureBenches ] listBenches = [ bench "map" $ nf (map (+1)) [1..10000] , bench "filter" $ nf (filter odd) [1..10000] , bench "sort" $ nf sort [10000,9999..1] ] ``` -------------------------------- ### Benchmark Type Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Defines the structure for specifying benchmarks, including single benchmarks, groups, and environment setup. ```APIDOC ## Benchmark Type ### Description A benchmark specification describing what to measure. It can represent a single benchmark, a named group of benchmarks, or a benchmark with environment setup and cleanup. ### Constructors - `Benchmark String Benchmarkable`: Represents a single named benchmark. - `BenchGroup String [Benchmark]`: Represents a named group of benchmarks. - `Environment setup cleanup setup -> Benchmark`: Represents a benchmark with associated setup and cleanup actions. ``` -------------------------------- ### Get Previous Item in Array Source: https://github.com/haskell/criterion/blob/master/www/report.html Returns the previous item in an array, optionally wrapping around to the end. ```javascript H.previousItem=function(t,e,n){return n?e<=0?t[t.length-1]:t[e-1]:e<=0?t[0]:t[e-1]} ``` -------------------------------- ### Organizing Benchmarks by Module/Feature Source: https://github.com/haskell/criterion/blob/master/_autodocs/benchmarking-guide.md Demonstrates how to structure a large benchmark suite in Haskell using Criterion by grouping benchmarks into logical categories like algorithms, data structures, and I/O operations. ```haskell -- Group by module/feature main = defaultMain [ algBenches , dataStructureBenches , ioBenches ] algBenches = bgroup "algorithms" [...] dataStructureBenches = bgroup "data structures" [...] ioBenches = bgroup "io" [...] ``` -------------------------------- ### Get Next Item in Array Source: https://github.com/haskell/criterion/blob/master/www/report.html Returns the next item in an array, optionally wrapping around to the beginning. ```javascript H.nextItem=function(t,e,n){return n?e>=t.length-1?t[0]:t[e+1]:e>=t.length-1?t[t.length-1]:t[e+1]} ``` -------------------------------- ### Scale Initialization and Update Source: https://github.com/haskell/criterion/blob/master/www/fibber.html Sets up the initial state and update logic for a chart scale. It handles maximum dimensions, margins, and tick generation, preparing the scale for rendering. ```javascript var xn=K.extend({zeroLineIndex:0,getPadding:function(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}},getTicks:function(){return this._ticks},_getLabels:function(){var t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]},mergeTicksOptions:function(){},beforeUpdate:function(){H.callback(this.options.beforeUpdate,[this])},update:function(t,e,n){var i,a,r,o,s,l=this,u=l.options.ticks,d=u.sampleSize;if(l.beforeUpdate(),l.maxWidth=t,l.maxHeight=e,l.margins=H.extend({left:0,right:0,top:0,bottom:0},n),l._ticks=null,l.ticks=null,l._labelSizes=null,l._maxLabelLin ``` -------------------------------- ### Get Fill Target Type Source: https://github.com/haskell/criterion/blob/master/www/report.html Determines the type of fill target (dataset or boundary) for a given element. ```javascript function xi(t){var e=t.fill,n="dataset";return!1===e?null:(isFinite(e)||(n="boundary"),pi[n](t))} ``` -------------------------------- ### Get Ring Weight Source: https://github.com/haskell/criterion/blob/master/www/report.html Retrieves the weight of a dataset, defaulting to 1 if not specified. Ensures the weight is non-negative. ```javascript _getRingWeight:function(t){return Math.max(Lt(this.chart.data.datasets[t].weight,1),0)} ``` -------------------------------- ### Chart.js Initialization and Configuration Source: https://github.com/haskell/criterion/blob/master/www/report.html Initializes a new Chart.js instance with specified data and options. Supports various chart types like Bar, Line, Pie, etc. Requires Chart.js library to be included. ```javascript var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); ``` -------------------------------- ### Execute Criterion computation with configuration Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-monad.md Use `withConfig` to run benchmark operations with a specific configuration. This function handles initialization and potential side effects like console output or temporary file creation. ```haskell import Criterion.Monad import Criterion.Main.Options import Criterion.Types let cfg = defaultConfig { timeLimit = 10 } result <- withConfig cfg $ do -- Run benchmark operations return () ``` -------------------------------- ### Benchmark Data Type Definition Source: https://github.com/haskell/criterion/blob/master/_autodocs/types.md Defines the structure for a single benchmark, a group of benchmarks, or benchmarks with environment setup and cleanup. ```haskell data Benchmark = Benchmark String Benchmarkable -- Single benchmark | BenchGroup String [Benchmark] -- Group of benchmarks | Environment (IO a) -- Setup (a -> IO ()) -- Cleanup (a -> Benchmark) -- Create benchmark(s) ``` -------------------------------- ### Run with Higher Precision Source: https://github.com/haskell/criterion/blob/master/_autodocs/configuration.md Configure the confidence interval and bootstrap resamples for more precise benchmark analysis. ```bash cabal run mybench -- -I 0.99 --resamples 5000 ``` -------------------------------- ### Get Maximum Height for Element Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates the maximum available height for an element, considering its parent's padding and its own constraints. ```javascript H.getMaximumHeight=function(t){var e=H._getParentNode(t);if(!e)return t.clientHei ``` -------------------------------- ### Default Benchmark Execution Source: https://github.com/haskell/criterion/blob/master/_autodocs/api-reference/criterion-main.md Use `defaultMain` to run benchmarks with default settings. It parses command-line arguments and applies a 95% confidence interval, 5-second time limit, and 1000 bootstrap resamples. ```haskell import Criterion.Main fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) main = defaultMain [ bgroup "fib" [ bench "1" $ whnf fib 1 , bench "5" $ whnf fib 5 , bench "10" $ whnf fib 10 ] ] ``` -------------------------------- ### Get Maximum Width for Element Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates the maximum available width for an element, considering its parent's padding and its own constraints. ```javascript H.getMaximumWidth=function(t){var e=H._getParentNode(t);if(!e)return t.clientWidth;var n=e.clientWidth,i=n-H._calculatePadding(e,"padding-left",n)-H._calculatePadding(e,"padding-right",n),a=H.getConstraintWidth(t);return isNaN(a)?i:Math.min(i,a)} ``` -------------------------------- ### Get Boundary Points Source: https://github.com/haskell/criterion/blob/master/www/report.html Calculates boundary points for fill operations, handling different scale types and fill modes. ```javascript function vi(t){return(t.el._scale||{}).getPointPositionForValue?function(t){var e,n,i,a,r,o=t.el._scale,s=o.options,l=o.chart.data.labels.length,u=t.fill,[d]=[],c=0,f=0;if(!l)return null;for(e=s.ticks.reverse?o.max:o.min,n=s.ticks.reverse?o.min:o.max,i=o.getPointPositionForValue(0,e),a=0;a