packages feed

lynceus (empty) → 0.0.1.0

raw patch · 13 files changed

+1748/−0 lines, 13 filesdep +basedep +containersdep +deepseq

Dependencies added: base, containers, deepseq, directory, filepath, hspec, lynceus, temporary, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,3 @@+## Lynceus 0.0.1.0++* Initial release.
+ LICENSE.md view
@@ -0,0 +1,28 @@+Copyright © 2026–present Mark Karpov++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice,+  this list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright+  notice, this list of conditions and the following disclaimer in the+  documentation and/or other materials provided with the distribution.++* Neither the name Mark Karpov nor the names of contributors may be used to+  endorse or promote products derived from this software without specific+  prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS “AS IS” AND ANY EXPRESS+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN+NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,+OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,+EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,153 @@+# Lynceus++* [Quick start](#quick-start)+* [What is checked](#what-is-checked)+* [In CI](#in-ci)+* [Comparing two versions](#comparing-two-versions)+* [Contribution](#contribution)+* [License](#license)++Lynceus is a benchmarking library designed to reliably guard against the+smallest performance regressions. It measures both allocations and+instructions retired in user space. For the latter it relies on+[perf_events], so that functionality is Linux-specific and suits developers+on Linux best.++When we measure time, a regression of a fraction of a percent cannot be told+from noise however careful the statistics. What a piece of work allocates+and the instructions it retires, on the other hand, are the same from one+run to the next to a hundredth of a percent. That makes it possible to keep+them in the repository and check them on every change, like a golden test.++Lynceus was originally designed to aid development of [Tilia][tilia] and+[Megaparsec 10][megaparsec].++[perf_events]: https://en.wikipedia.org/wiki/Perf_%28Linux%29+[tilia]: https://github.com/mrkkrp/tilia+[megaparsec]: https://github.com/mrkkrp/megaparsec++## Quick start++Add a benchmark to the Cabal file. It must be built so that the RTS collects+statistics (`-T`) and garbage collections (`-A1g -O1g`) and context switches+(`-C1000`) do not fall inside a run, since those make the counts depend on+the rest of the heap and on the clock:++```cabal+benchmark bench+    type:             exitcode-stdio-1.0+    main-is:          Main.hs+    hs-source-dirs:   bench+    build-depends:+        base,+        lynceus+    ghc-options: -O2 -rtsopts "-with-rtsopts=-A1g -O1g -C1000 -T"+```++Then write the benchmarks:++```haskell+import Data.List (sort)+import Lynceus++main :: IO ()+main =+  defaultMain+    "bench/bench.record"+    [ group+        "sort"+        [ bench "ascending" (nf sort [1 .. 100000 :: Int]),+          bench "descending" (nf sort [100000, 99999 .. 1 :: Int])+        ]+    ]+```++`nf` applies a function to an argument and evaluates the result to normal+form. Consult the Haddocks for a full overview of the API.++Write the record and commit it:++```console+$ LYNCEUS_ACCEPT=1 cabal bench+```++From then on `cabal bench` checks the benchmarks against it and fails if+they moved:++```+sort         7.218 MB (+0.27%)!   20.14 M instr (+0.37%)!+  ascending  4.797 MB (+0.00%)    10.72 M instr (+0.00%)+  descending 2.420 MB (+0.80%)!   9.425 M instr (+0.80%)!++The costs marked with ! moved further than the tolerances allow.++If that is the intended change, write the record again:+    LYNCEUS_ACCEPT=1 cabal bench+```++The record is a plain text file that lists what each benchmark allocates and+the instructions it retires, sorted by group and name, along with the+compiler the benchmarks were built with and the processor the instructions+were counted on. A change to it shows in review like any other, so an+intended regression or improvement is accepted explicitly. Writing it again+keeps the costs that moved no further than two runs of one build differ, so+that the diff shows only what moved.++## What is checked++A run fails where a benchmark allocates or retires 0.5% more or less than+its record or where all the benchmarks of a group together deviate by 0.05%.+Run the benchmark with `--help` to see the options that change these+tolerances, or set other defaults in code with `defaultMainWith`.++A run also fails on a benchmark that is not in the record, which the report+marks `(new)`, and on one that is in the record but was not run, unless+`--match` selected only some of them.++What is allocated depends on the compiler, so it is included in the record,+and the run fails if there is a mismatch. The instructions depend on the+processor as well, so they are checked only on the processor the record+names, where Linux lets a process count them. Elsewhere the run says so and+checks the rest.++## In CI++Write the record on the machine you develop on and check it in CI. What is+allocated does not depend on the processor, only on the code that runs, so+CI checks the allocations as long as it builds the benchmarks the same way:+with the compiler the record names, the same flags, and the same versions of+the dependencies, which an `index-state` in `cabal.project` or a+`cabal.project.freeze` pins. A dependency that changes between the two moves+the allocations just like a regression would.++The processor of a CI runner is rarely the one the record names, and virtual+machines often hide the hardware counters, so *CI checks only the+allocations*. Running the benchmarks locally before pushing checks both,+which catches regressions in instruction counts. Instruct your agents to run+the benchmarks on every change.++## Comparing two versions++Time is not recorded or checked, but to compare two versions on a machine+with a different processor from the one in the record, you can create a+baseline explicitly and compare against that. This shows the time and the+instructions of all the benchmarks together and the benchmarks that moved+most:++```console+$ cabal bench --benchmark-options='--save /tmp/before'+$ cabal bench --benchmark-options='--baseline /tmp/before'+```++## Contribution++Issues, bugs, and questions may be reported in [the GitHub issue tracker for+this project](https://github.com/mrkkrp/lynceus/issues).++Pull requests are also welcome.++## License++Copyright © 2026–present Mark Karpov++Distributed under the BSD 3-clause license.
+ bench/Main.hs view
@@ -0,0 +1,29 @@+module Main (main) where++import Data.Foldable (for_)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.List (sort)++import Lynceus++main :: IO ()+main =+  defaultMain+    "bench/bench.record"+    [ group+        "sort"+        [ bench "ascending" (nf sort [1 .. 100000 :: Int]),+          bench "descending" (nf sort [100000, 99999 .. 1 :: Int])+        ],+      group+        "list"+        [ bench "reverse" (whnf reverse [1 .. 100000 :: Int]),+          bench "accumulate" (withSetup (newIORef 0) (nfIO . accumulate))+        ]+    ]++-- | Add the numbers up to 100000 to a reference and read it.+accumulate :: IORef Int -> IO Int+accumulate ref = do+  for_ [1 .. 100000] $ \i -> modifyIORef' ref (+ i)+  readIORef ref
+ cbits/counter.c view
@@ -0,0 +1,46 @@+#include <stdint.h>++#ifdef __linux__++#include <linux/perf_event.h>+#include <string.h>+#include <sys/syscall.h>+#include <unistd.h>++/* Open a counter of the instructions the calling thread retires in user+   space, giving -1 where the system does not let a process count them. */+int lynceus_counter_open(void)+{+  struct perf_event_attr attr;+  memset(&attr, 0, sizeof attr);+  attr.type = PERF_TYPE_HARDWARE;+  attr.size = sizeof attr;+  attr.config = PERF_COUNT_HW_INSTRUCTIONS;+  attr.exclude_kernel = 1;+  attr.exclude_hv = 1;+  return syscall(SYS_perf_event_open, &attr, 0, -1, -1, 0);+}++/* Read a counter. */+uint64_t lynceus_counter_read(int fd)+{+  uint64_t count = 0;+  if (read(fd, &count, sizeof count) != sizeof count)+    return 0;+  return count;+}++#else++int lynceus_counter_open(void)+{+  return -1;+}++uint64_t lynceus_counter_read(int fd)+{+  (void)fd;+  return 0;+}++#endif
+ lynceus.cabal view
@@ -0,0 +1,98 @@+cabal-version:   2.4+name:            lynceus+version:         0.0.1.0+license:         BSD-3-Clause+license-file:    LICENSE.md+maintainer:      Mark Karpov <markkarpov92@gmail.com>+author:          Mark Karpov <markkarpov92@gmail.com>+tested-with:     ghc ==9.10.3 ghc ==9.12.4 ghc ==9.14.1+homepage:        https://github.com/mrkkrp/lynceus+bug-reports:     https://github.com/mrkkrp/lynceus/issues+synopsis:+    Deterministic benchmarks for catching tiny performance regressions++description:+    Deterministic benchmarks for catching tiny performance regressions.++category:        Benchmarking, Performance+build-type:      Simple+extra-doc-files:+    CHANGELOG.md+    README.md++source-repository head+    type:     git+    location: https://github.com/mrkkrp/lynceus.git++flag dev+    description: Turn on development settings.+    default:     False+    manual:      True++library+    exposed-modules:+        Lynceus+        Lynceus.Benchmark+        Lynceus.Measure+        Lynceus.Options+        Lynceus.Record+        Lynceus.Run++    c-sources:        cbits/counter.c+    hs-source-dirs:   src+    default-language: GHC2021+    build-depends:+        base >=4.15 && <5,+        containers >=0.6.0.1 && <0.9,+        deepseq >=1.4 && <1.6,+        directory >=1.3 && <1.4,+        text >=2.1 && <2.2++    if flag(dev)+        ghc-options:+            -Wall -Werror -Wredundant-constraints -Wpartial-fields+            -Wunused-packages -haddock -Winvalid-haddock++    else+        ghc-options: -O2 -Wall++test-suite tests+    type:             exitcode-stdio-1.0+    main-is:          Main.hs+    hs-source-dirs:   tests+    default-language: GHC2021+    ghc-options:      -rtsopts -with-rtsopts=-T+    build-depends:+        base >=4.15 && <5,+        containers >=0.6.0.1 && <0.9,+        filepath >=1.4 && <1.6,+        hspec >=2 && <3,+        lynceus,+        temporary >=1.1 && <1.4,+        text >=2.1 && <2.2++    if flag(dev)+        ghc-options:+            -Wall -Werror -Wredundant-constraints -Wpartial-fields+            -Wunused-packages -haddock -Winvalid-haddock++    else+        ghc-options: -O2 -Wall++benchmark bench+    type:             exitcode-stdio-1.0+    main-is:          Main.hs+    hs-source-dirs:   bench+    default-language: GHC2021+    ghc-options:      -rtsopts "-with-rtsopts=-A1g -O1g -C1000 -T"+    build-depends:+        base >=4.15 && <5,+        lynceus++    if flag(dev)+        ghc-options:+            -Wall -Werror -Wredundant-constraints -Wpartial-fields+            -Wunused-packages -haddock -Winvalid-haddock++    else+        ghc-options: -O2 -Wall
+ src/Lynceus.hs view
@@ -0,0 +1,114 @@+-- |+-- Module      :  Lynceus+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- Benchmarks that measure allocations and, where Linux lets a process count+-- them, the instructions it retires in user space. Both are the same from+-- one run to the next to a hundredth of a percent, so they are kept in a+-- record in the repository and checked like a golden test, which catches+-- regressions far smaller than timing can.+--+-- > import Data.List (sort)+-- > import Lynceus+-- >+-- > main :: IO ()+-- > main =+-- >   defaultMain+-- >     "bench/bench.record"+-- >     [ group+-- >         "sort"+-- >         [ bench "ascending" (nf sort [1 .. 100000 :: Int]),+-- >           bench "descending" (nf sort [100000, 99999 .. 1 :: Int])+-- >         ]+-- >     ]+--+-- The benchmark must be built so that the RTS collects statistics and+-- collections and context switches do not fall inside a run, which would+-- make the counts depend on the rest of the heap and on the clock:+--+-- > ghc-options: -rtsopts "-with-rtsopts=-A1g -O1g -C1000 -T"+--+-- Run the benchmarks with @LYNCEUS_ACCEPT=1@ to write the record, and+-- without it to check it.+module Lynceus+  ( -- * Running+    defaultMain,+    defaultMainWith,++    -- * Options+    Options (..),+    defaultOptions,++    -- * Benchmarks+    Group,+    group,+    Bench,+    bench,++    -- * Work+    Work,+    nf,+    whnf,+    nfIO,+    whnfIO,+    withSetup,+    withSetupWhnf,+  )+where++import Control.Monad (unless)+import Data.Text.IO qualified as T+import GHC.Stats (getRTSStatsEnabled)+import System.Environment (getArgs, lookupEnv)+import System.Exit (die, exitFailure, exitSuccess)+import System.IO+  ( BufferMode (..),+    hSetBuffering,+    hSetEncoding,+    stderr,+    stdout,+    utf8,+  )++import Lynceus.Benchmark+import Lynceus.Measure+import Lynceus.Options+import Lynceus.Run++-- | Measure the benchmarks and check what they cost against the record at+-- the given path, or write the record anew where @LYNCEUS_ACCEPT@ is set to+-- anything but empty, @0@, @no@, or @false@.+defaultMain :: FilePath -> [Group] -> IO ()+defaultMain = defaultMainWith defaultOptions++-- | 'defaultMain' with the given options as the defaults that the command+-- line overrides.+defaultMainWith :: Options -> FilePath -> [Group] -> IO ()+defaultMainWith defaults path groups = do+  hSetBuffering stdout LineBuffering+  hSetEncoding stdout utf8+  hSetEncoding stderr utf8+  enabled <- getRTSStatsEnabled+  unless enabled $+    die+      "The RTS does not collect statistics: build the benchmark with\n\+      \    ghc-options: -rtsopts \"-with-rtsopts=-A1g -O1g -C1000 -T\""+  options <-+    getArgs >>= \args -> case parseArguments defaults args of+      Left err -> die (err <> "\n" <> usage defaults)+      Right Nothing -> putStr (usage defaults) >> exitSuccess+      Right (Just options) -> pure options+  case validate groups of+    [] -> pure ()+    problems -> die (unlines (explain <$> problems))+  accepting <-+    maybe False (`notElem` ["", "0", "no", "false"])+      <$> lookupEnv "LYNCEUS_ACCEPT"+  passed <-+    run options (if accepting then Accept else Check) T.putStrLn path groups+  unless passed exitFailure
+ src/Lynceus/Benchmark.hs view
@@ -0,0 +1,128 @@+{-# LANGUAGE LambdaCase #-}++-- |+-- Module      :  Lynceus.Benchmark+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- Benchmarks and the groups they are checked in.+module Lynceus.Benchmark+  ( Bench,+    benchName,+    benchWork,+    Group,+    group,+    bench,+    groupName,+    groupBenchmarks,+    Problem (..),+    validate,+    explain,+  )+where++import Data.List (intercalate, isPrefixOf)+import Data.Map.Strict qualified as Map++import Lynceus.Measure++-- | A piece of work to measure.+data Bench = Bench String Work++-- | Name a piece of work.+bench :: String -> Work -> Bench+bench = Bench++-- | The name of a benchmark, unique within its group.+benchName :: Bench -> String+benchName (Bench name _) = name++-- | The work a benchmark measures.+benchWork :: Bench -> Work+benchWork (Bench _ work) = work++-- | Benchmarks whose costs are also checked together.+data Group = Group String [Bench]++-- | Group benchmarks under a name, a single word.+group :: String -> [Bench] -> Group+group = Group++-- | The name of a group, a single word.+groupName :: Group -> String+groupName (Group name _) = name++-- | The benchmarks of a group.+groupBenchmarks :: Group -> [Bench]+groupBenchmarks (Group _ benchmarks) = benchmarks++-- | What is wrong with the name of a group or a benchmark.+data Problem+  = -- | A group not named by a single word.+    InvalidGroupName String+  | -- | A group named @compiler@ or @processor@ or starting with @#@, which+    -- the record would misread.+    ReservedGroupName String+  | -- | A group named more than once.+    DuplicateGroupName String+  | -- | A benchmark not named by words separated by single spaces, by the+    -- names of its group and its own.+    InvalidBenchName String String+  | -- | A benchmark named more than once in a group, by the names of the+    -- group and the benchmark.+    DuplicateBenchName String String+  deriving (Eq, Show)++-- | What is wrong with the names of the groups and benchmarks.+validate :: [Group] -> [Problem]+validate groups =+  [InvalidGroupName g | g <- names, not (word g)]+    <> [ ReservedGroupName g+       | g <- names,+         word g,+         g `elem` reserved || "#" `isPrefixOf` g+       ]+    <> [DuplicateGroupName g | g <- repeated names]+    <> [ InvalidBenchName (groupName g) n+       | g <- groups,+         n <- benchName <$> groupBenchmarks g,+         null n || unwords (words n) /= n+       ]+    <> [ DuplicateBenchName (groupName g) n+       | g <- groups,+         n <- repeated (benchName <$> groupBenchmarks g)+       ]+  where+    names = groupName <$> groups+    word t = words t == [t]+    repeated xs =+      Map.keys+        (Map.filter (> (1 :: Int)) (Map.fromListWith (+) [(x, 1) | x <- xs]))++-- | Explain a problem in a line.+explain :: Problem -> String+explain = \case+  InvalidGroupName g ->+    "A group must be named by a single word: " <> quoted g+  ReservedGroupName g ->+    "A group must not be named "+      <> intercalate " or " reserved+      <> " or start with #: "+      <> quoted g+  DuplicateGroupName g -> "Group named more than once: " <> g+  InvalidBenchName g n ->+    "A benchmark must be named by words separated by single spaces: "+      <> g+      <> " "+      <> quoted n+  DuplicateBenchName g n -> "Benchmark named more than once: " <> g <> " " <> n+  where+    quoted t = "\"" <> t <> "\""++-- | The words that start the lines of the record's header.+reserved :: [String]+reserved = ["compiler", "processor"]
+ src/Lynceus/Measure.hs view
@@ -0,0 +1,158 @@+{-# OPTIONS_GHC -fno-full-laziness #-}++-- |+-- Module      :  Lynceus.Measure+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- Measuring what a piece of work costs.+module Lynceus.Measure+  ( -- * Work+    Work,+    nf,+    whnf,+    nfIO,+    whnfIO,+    withSetup,+    withSetupWhnf,++    -- * Measurement+    Counter,+    openCounter,+    Measurement (..),+    measure,+  )+where++import Control.Concurrent (yield)+import Control.DeepSeq (NFData, force, rnf)+import Control.Exception (evaluate)+import Control.Monad (replicateM, void)+import Data.Int (Int64)+import Data.Word (Word64)+import Foreign.C.Types (CInt (..))+import GHC.Stats (RTSStats (..), getRTSStats)+import System.Mem (getAllocationCounter, performMajorGC)++-- | Work to measure.+newtype Work = Work (IO (IO ()))++-- | Apply a function to an argument and evaluate the result to normal form.+nf :: NFData b => (a -> b) -> a -> Work+nf f x = Work (pure (applied rnf f x))+{-# NOINLINE nf #-}++-- | Apply a function to an argument and evaluate the result to weak head+-- normal form.+whnf :: (a -> b) -> a -> Work+whnf f x = Work (pure (applied (`seq` ()) f x))+{-# NOINLINE whnf #-}++-- | Apply a function to an argument and evaluate the result with the given+-- function, building the application anew every time.+applied :: (b -> ()) -> (a -> b) -> a -> IO ()+applied evaluated f x = evaluate (evaluated (f x))+{-# NOINLINE applied #-}++-- | Run an action and evaluate its result to normal form.+nfIO :: NFData a => IO a -> Work+nfIO action = Work (pure (action >>= evaluate . rnf))++-- | Run an action and evaluate its result to weak head normal form.+whnfIO :: IO a -> Work+whnfIO action = Work (pure (void (action >>= evaluate)))++-- | Run a preparatory step with its result evaluated to normal form and+-- left out of the measurement.+withSetup :: NFData a => IO a -> (a -> Work) -> Work+withSetup setup = withSetupWhnf (setup >>= evaluate . force)++-- | Run a preparatory step with its result evaluated to weak head normal+-- form and left out of the measurement. This suits what has no normal form+-- to evaluate to, such as mutable state, a handle, or the work itself.+withSetupWhnf :: IO a -> (a -> Work) -> Work+withSetupWhnf setup work = Work $ do+  prepared <- setup >>= evaluate+  let Work set = work prepared+  set++-- | A counter of the instructions the thread that opened it retires in user+-- space.+newtype Counter = Counter CInt++foreign import ccall unsafe "lynceus_counter_open"+  counterOpen :: IO CInt++foreign import ccall unsafe "lynceus_counter_read"+  counterRead :: CInt -> IO Word64++-- | Open a counter, where the system lets a process count its own+-- instructions.+openCounter :: IO (Maybe Counter)+openCounter = do+  fd <- counterOpen+  pure (if fd < 0 then Nothing else Just (Counter fd))++-- | What a piece of work cost.+data Measurement = Measurement+  { -- | The bytes the thread running it allocated.+    measuredAllocated :: !Word64,+    -- | The instructions it retired, where they were counted.+    measuredInstructions :: !(Maybe Word64),+    -- | The CPU time it took, in nanoseconds, the least of the runs.+    measuredTime :: !Int64,+    -- | How far apart the runs' allocations were, as a fraction.+    measuredSpread :: !Double+  }+  deriving (Eq, Show)++-- | Run a piece of work once to warm up and then the given number of+-- times.+measure ::+  -- | The counter of instructions, if there is one.+  Maybe Counter ->+  -- | How many runs to measure.+  Int ->+  -- | The work.+  Work ->+  IO Measurement+measure counter runs (Work set) = do+  _ <- once+  samples <- replicateM (max 1 runs) once+  let allocations = [a | (a, _, _) <- samples]+      (allocated, instructions, _) = last samples+  pure+    Measurement+      { measuredAllocated = allocated,+        measuredInstructions = instructions,+        measuredTime = minimum [t | (_, _, t) <- samples],+        measuredSpread =+          fromIntegral (maximum allocations - minimum allocations)+            / fromIntegral (max 1 (minimum allocations))+      }+  where+    count = traverse (\(Counter fd) -> counterRead fd) counter+    once = do+      work <- set+      performMajorGC+      yield+      performMajorGC+      before <- getRTSStats+      -- The thread's own counter takes every allocation as it happens,+      -- while the RTS's total takes pinned ones a block at a time.+      allowance <- getAllocationCounter+      started <- count+      work+      ended <- count+      remaining <- getAllocationCounter+      performMajorGC+      after <- getRTSStats+      pure+        ( fromIntegral (allowance - remaining),+          (-) <$> ended <*> started,+          cpu_ns after - cpu_ns before+        )
+ src/Lynceus/Options.hs view
@@ -0,0 +1,149 @@+{-# LANGUAGE LambdaCase #-}++-- |+-- Module      :  Lynceus.Options+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- The options of a run and the command line that sets them.+module Lynceus.Options+  ( Options (..),+    defaultOptions,+    parseArguments,+    usage,+  )+where++import Control.Monad (foldM)+import Data.List (dropWhileEnd)+import Data.Text (Text)+import Data.Text qualified as T+import System.Console.GetOpt+import Text.Printf (printf)+import Text.Read (readMaybe)++-- | How the benchmarks were asked to run.+data Options = Options+  { -- | How many runs to measure after the one that warms up.+    optRuns :: Int,+    -- | Run only the benchmarks whose group or name holds this.+    optMatch :: Maybe Text,+    -- | How far one benchmark's allocations or instructions may move from+    -- the record, as a fraction.+    optTolerance :: Double,+    -- | How far the allocations or instructions of all the benchmarks of a+    -- group may move together, as a fraction.+    optGroupTolerance :: Double,+    -- | Where to save the time and instructions of every benchmark.+    optSave :: Maybe FilePath,+    -- | What an earlier run saved, to compare this one with.+    optBaseline :: Maybe FilePath+  }+  deriving (Eq, Show)++-- | The options of a run that is given none.+defaultOptions :: Options+defaultOptions =+  Options+    { optRuns = 1,+      optMatch = Nothing,+      optTolerance = 0.005,+      optGroupTolerance = 0.0005,+      optSave = Nothing,+      optBaseline = Nothing+    }++-- | What one command line argument asks for.+data Setting+  = Help+  | Set (Options -> Either String Options)++-- | Parse the command line on top of the given options, giving 'Nothing'+-- where it asks for help.+parseArguments :: Options -> [String] -> Either String (Maybe Options)+parseArguments options args =+  case getOpt Permute (descriptions options) args of+    (settings, [], [])+      | any isHelp settings -> Right Nothing+      | otherwise -> Just <$> foldM applied options settings+    (_, extra, errors) ->+      Left+        (concat errors <> concatMap (\a -> "unexpected " <> a <> "\n") extra)+  where+    isHelp = \case+      Help -> True+      Set _ -> False+    applied o = \case+      Help -> Right o+      Set f -> f o++-- | The usage text, giving the given options as the defaults.+usage :: Options -> String+usage options =+  usageInfo+    "Measure what the benchmarks cost and check it against the record.\n\n\+    \Usage: BENCHMARK [OPTIONS]\n"+    (descriptions options)++-- | The options of the command line, with the given options as the+-- defaults.+descriptions :: Options -> [OptDescr Setting]+descriptions defaults =+  [ Option+      []+      ["runs"]+      (ReqArg (\s -> Set (\o -> (\n -> o{optRuns = n}) <$> positive s)) "N")+      ( "How many runs to measure after the one that warms up"+          <> defaulting (show (optRuns defaults))+      ),+    Option+      []+      ["match"]+      (ReqArg (\s -> Set (\o -> Right o{optMatch = Just (T.pack s)})) "TEXT")+      "Run only the benchmarks whose group or name holds TEXT",+    Option+      []+      ["tolerance"]+      ( ReqArg+          (\s -> Set (\o -> (\x -> o{optTolerance = x}) <$> percent s))+          "PERCENT"+      )+      ( "How far one benchmark may move from the record"+          <> defaulting (percentage (optTolerance defaults))+      ),+    Option+      []+      ["group-tolerance"]+      ( ReqArg+          (\s -> Set (\o -> (\x -> o{optGroupTolerance = x}) <$> percent s))+          "PERCENT"+      )+      ( "How far the benchmarks of a group may move together"+          <> defaulting (percentage (optGroupTolerance defaults))+      ),+    Option+      []+      ["save"]+      (ReqArg (\s -> Set (\o -> Right o{optSave = Just s})) "FILE")+      "Save the time and instructions of every benchmark to FILE",+    Option+      []+      ["baseline"]+      (ReqArg (\s -> Set (\o -> Right o{optBaseline = Just s})) "FILE")+      "Compare with what an earlier run saved to FILE",+    Option [] ["help"] (NoArg Help) "Show this help text"+  ]+  where+    positive s = case readMaybe s of+      Just n | n > 0 -> Right n+      _ -> Left ("not a positive number of runs: " <> s <> "\n")+    percent s = case readMaybe s of+      Just x | x >= 0 -> Right (x / 100)+      _ -> Left ("not a percentage: " <> s <> "\n")+    defaulting value = " (default: " <> value <> ")"+    percentage x =+      dropWhileEnd (== '.') (dropWhileEnd (== '0') (printf "%.4f" (100 * x)))
+ src/Lynceus/Record.hs view
@@ -0,0 +1,138 @@+{-# LANGUAGE OverloadedStrings #-}++-- |+-- Module      :  Lynceus.Record+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- Operations on 'Record's.+module Lynceus.Record+  ( Key (..),+    Record (..),+    Entry (..),+    emptyRecord,+    parseRecord,+    renderRecord,+    readRecord,+    writeRecord,+  )+where++import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO.Utf8 qualified as T+import Data.Word (Word64)+import System.Directory (doesFileExist)+import Text.Read (readMaybe)++-- | A benchmark, by group and name.+data Key = Key Text Text+  deriving (Eq, Ord, Show)++-- | The bytes each benchmark allocated and the instructions it retired.+data Record = Record+  { -- | The compiler the record was made with, which what is allocated+    -- depends on.+    recordCompiler :: Text,+    -- | The processor the instructions were counted on, which how many+    -- there are depends on, or @none@.+    recordProcessor :: Text,+    -- | One entry for every benchmark.+    recordEntries :: Map Key Entry+  }+  deriving (Eq, Show)++-- | What one benchmark cost.+data Entry = Entry+  { -- | The bytes it allocated.+    entryAllocated :: !Word64,+    -- | The instructions it retired, where they were counted.+    entryInstructions :: !(Maybe Word64)+  }+  deriving (Eq, Show)++-- | The record of no benchmarks.+emptyRecord :: Record+emptyRecord = Record "" "none" Map.empty++-- | Read a record from what 'renderRecord' wrote.+parseRecord :: Text -> Record+parseRecord text =+  Record+    { recordCompiler = field "compiler ",+      recordProcessor = field "processor ",+      recordEntries = Map.fromList (mapMaybe entry ls)+    }+  where+    ls = T.stripEnd <$> T.lines text+    field key = mconcat (mapMaybe (T.stripPrefix key) ls)+    entry line = case T.words line of+      group : allocated : instructions : name@(_ : _)+        | Just a <- readMaybe (T.unpack allocated) ->+            Just+              ( Key group (T.unwords name),+                Entry a (readMaybe (T.unpack instructions))+              )+      _ -> Nothing++-- | Render a record, sorted by group and name so that a regeneration diff+-- shows what changed rather than what moved.+renderRecord :: Record -> Text+renderRecord record =+  T.unlines $+    [ "# The benchmark record. Run with LYNCEUS_ACCEPT=1 to overwrite.",+      "#",+      "# compiler    The compiler the benchmarks were built with, which what",+      "#             they allocate depends on.",+      "# processor   The processor the instructions were counted on, which",+      "#             how many there are depends on, or none.",+      "#",+      "# Every other line is a benchmark:",+      "#",+      "# group         The group of the benchmark.",+      "# allocated     The bytes it allocates.",+      "# instructions  The instructions it retires in user space, or - where",+      "#               they were not counted.",+      "# benchmark     The name of the benchmark.",+      "",+      "compiler " <> recordCompiler record,+      "processor " <> recordProcessor record,+      "",+      row "# group" ["allocated", "instructions"] "benchmark"+    ]+      <> fmap line (Map.toAscList (recordEntries record))+  where+    line (Key group name, Entry allocated instructions) =+      row group [shown allocated, maybe "-" shown instructions] name+    row group costs name =+      T.justifyLeft width ' ' group+        <> foldMap (T.justifyRight 14 ' ') costs+        <> "  "+        <> name+    width =+      maximum+        (8 : [T.length g + 1 | Key g _ <- Map.keys (recordEntries record)])+    shown = T.pack . show++-- | Read a record, where a missing one is empty, so that benchmarks added+-- before it is written each say they are not in it.+--+-- A missing record is not read at all, since the exception that reading+-- it throws changes what the first benchmark allocates.+readRecord :: FilePath -> IO Record+readRecord path = do+  there <- doesFileExist path+  if there+    then parseRecord <$> T.readFile path+    else pure emptyRecord++-- | Write a record.+writeRecord :: FilePath -> Record -> IO ()+writeRecord path = T.writeFile path . renderRecord
+ src/Lynceus/Run.hs view
@@ -0,0 +1,463 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}++-- |+-- Module      :  Lynceus.Run+-- Copyright   :  © 2026–present Mark Karpov+-- License     :  BSD 3 clause+--+-- Maintainer  :  Mark Karpov <markkarpov92@gmail.com>+-- Stability   :  experimental+-- Portability :  portable+--+-- Measuring the benchmarks and checking them against the record.+module Lynceus.Run+  ( Mode (..),+    run,+    verdict,+    steadied,+  )+where++import Control.Applicative ((<|>))+import Control.Exception (SomeException, try)+import Control.Monad (unless)+import Data.Containers.ListUtils (nubOrd)+import Data.Foldable (for_)+import Data.Int (Int64)+import Data.List (sortOn)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe)+import Data.Ord (Down (..))+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO.Utf8 qualified as T+import Data.Traversable (for)+import Data.Version (showVersion)+import Data.Word (Word64)+import System.Info (fullCompilerVersion)+import Text.Printf (printf)+import Text.Read (readMaybe)++import Lynceus.Benchmark+  ( Group,+    benchName,+    benchWork,+    groupBenchmarks,+    groupName,+  )+import Lynceus.Measure+import Lynceus.Options+import Lynceus.Record++-- | What to do with the record.+data Mode+  = -- | Check what was measured against it.+    Check+  | -- | Write it anew from what was measured.+    Accept+  deriving (Eq, Show)++-- | Measure the benchmarks, say how that went, and check what they cost+-- against the record or write it anew, telling whether that succeeded.+run ::+  -- | The options.+  Options ->+  -- | What to do with the record.+  Mode ->+  -- | How to say a line of the report.+  (Text -> IO ()) ->+  -- | The record.+  FilePath ->+  -- | The benchmarks.+  [Group] ->+  IO Bool+run options mode say path groups = do+  counter <- openCounter+  processor <- maybe (pure Nothing) (const processorName) counter+  written <- readRecord path+  baseline <- traverse readBaseline (optBaseline options)+  let matching g b =+        maybe+          True+          ( \m ->+              m `T.isInfixOf` T.pack (groupName g)+                || m `T.isInfixOf` T.pack (benchName b)+          )+          (optMatch options)+      selected =+        [ (g, bs)+        | g <- groups,+          let bs = filter (matching g) (groupBenchmarks g),+          not (null bs)+        ]+      partial = isJust (optMatch options)+      record = comparable processor written+      width =+        maximum $+          1+            : [length (groupName g) | (g, _) <- selected]+              <> [2 + length (benchName b) | (_, bs) <- selected, b <- bs]+      reheaded =+        recordCompiler written /= compiler+          || recordProcessor written /= fromMaybe "none" processor+  measured <- fmap concat . for selected $ \(g, bs) -> do+    let group = T.pack (groupName g)+    ms <- for bs $ \b -> do+      m <- measure counter (optRuns options) (benchWork b)+      pure (Key group (T.pack (benchName b)), m)+    say (headerFor options width record group ms)+    for_ ms $ \(k, m) -> say (lineFor options width record k m)+    pure ms+  for_ (optSave options) (`writeBaseline` measured)+  for_ baseline (summarize say measured)+  case mode of+    Accept+      | partial && reheaded -> do+          say+            "\nOnly some benchmarks were run, on another compiler or\n\+            \processor than the record's: accept them all at once."+          pure False+      | otherwise -> do+          let entryOf k m =+                steadied (Map.lookup k (recordEntries record)) $+                  Entry+                    (measuredAllocated m)+                    (measuredInstructions m <* processor)+          writeRecord+            path+            Record+              { recordCompiler = compiler,+                recordProcessor = fromMaybe "none" processor,+                recordEntries =+                  Map.union+                    (Map.fromList [(k, entryOf k m) | (k, m) <- measured])+                    (if partial then recordEntries written else Map.empty)+              }+          say ("\nWrote " <> T.pack path <> ".")+          pure True+    Check -> do+      for_ (unchecked (isJust counter) processor record) $ \reason ->+        say ("\nInstructions are not checked: " <> reason <> ".")+      let problems = verdict options record partial measured+      unless (null problems) $ do+        say ""+        for_ problems say+        say ""+        say "If that is the intended change, write the record again:"+        say "    LYNCEUS_ACCEPT=1 cabal bench"+      pure (null problems)++-- | The compiler running the benchmarks.+compiler :: Text+compiler = T.pack ("ghc " <> showVersion fullCompilerVersion)++-- | The processor running the benchmarks, as Linux names it.+processorName :: IO (Maybe Text)+processorName =+  try (T.readFile "/proc/cpuinfo") >>= \case+    Left (_ :: SomeException) -> pure Nothing+    Right cpus ->+      pure $+        listToMaybe+          [ T.strip (T.drop 1 said)+          | (key, said) <- T.breakOn ":" <$> T.lines cpus,+            T.strip key == "model name"+          ]++-- | Forget the instructions a record counted on another processor than+-- this one.+comparable :: Maybe Text -> Record -> Record+comparable processor record+  | processor == Just (recordProcessor record) = record+  | otherwise =+      record+        { recordEntries =+            (\e -> e{entryInstructions = Nothing}) <$> recordEntries record+        }++-- | Why the instructions are not checked against the record, where they+-- are not.+unchecked :: Bool -> Maybe Text -> Record -> Maybe Text+unchecked counted processor record+  | not counted = Just "they cannot be counted here"+  | isNothing processor = Just "the processor is not known"+  | recordProcessor record == "none" = Just "the record has none"+  | processor /= Just (recordProcessor record) =+      Just ("the record counted them on " <> recordProcessor record)+  | otherwise = Nothing++-- | A group's line of the report: what its benchmarks allocated and the+-- instructions they retired together, against the record.+headerFor ::+  Options -> Int -> Record -> Text -> [(Key, Measurement)] -> Text+headerFor options width record group measured =+  T.stripEnd . T.pack $+    printf+      "%s %8s %-11s %s %s"+      (T.justifyLeft width ' ' group)+      (bytes (sum (measuredAllocated . snd <$> measured)))+      (changeOf allocations)+      ( instructionsColumn+          (sum <$> traverse (measuredInstructions . snd) measured)+      )+      (changeOf instructions)+  where+    changeOf cost =+      movement (optGroupTolerance options) cost (known record group measured)++-- | A benchmark's line of the report, under its group's: what it allocated+-- and the instructions it retired, against the record.+lineFor :: Options -> Int -> Record -> Key -> Measurement -> Text+lineFor options width record k@(Key _ name) m =+  T.stripEnd . T.pack $+    printf+      "%s %8s %-11s %s %-11s%s"+      (T.justifyLeft width ' ' ("  " <> name))+      (bytes (measuredAllocated m))+      (maybe "(new)" (changeOf allocations) entry)+      (instructionsColumn (measuredInstructions m))+      (maybe "" (changeOf instructions) entry)+      differing+  where+    entry = Map.lookup k (recordEntries record)+    changeOf cost e = movement (optTolerance options) cost [(e, m)]+    differing :: String+    differing+      | measuredSpread m > 0.001 =+          printf " (runs differ by %.2f%%)" (100 * measuredSpread m)+      | otherwise = ""++-- | A cost the record keeps for every benchmark.+data Cost = Cost+  { -- | What the record says it is.+    costRecorded :: Entry -> Maybe Word64,+    -- | What was measured.+    costMeasured :: Measurement -> Maybe Word64+  }++-- | The bytes allocated.+allocations :: Cost+allocations = Cost (Just . entryAllocated) (Just . measuredAllocated)++-- | The instructions retired, where they were counted.+instructions :: Cost+instructions = Cost entryInstructions measuredInstructions++-- | What the record says and what was measured of a cost, summed over the+-- benchmarks that have it on both sides.+summed :: Cost -> [(Entry, Measurement)] -> Maybe (Word64, Word64)+summed cost pairs =+  case [ (old, new)+       | (e, m) <- pairs,+         Just old <- [costRecorded cost e],+         Just new <- [costMeasured cost m]+       ] of+    [] -> Nothing+    both -> Just (sum (fmap fst both), sum (fmap snd both))++-- | How a cost moved against the record, as the report writes it, marked+-- where it moved further than the tolerance allows.+movement :: Double -> Cost -> [(Entry, Measurement)] -> String+movement tolerance cost pairs = case summed cost pairs of+  Nothing -> ""+  Just (old, new) ->+    against old new <> (if moved tolerance old new then "!" else "")++-- | What is wrong with the record, given what was measured, naming what+-- the lines of the report do not show.+verdict :: Options -> Record -> Bool -> [(Key, Measurement)] -> [Text]+verdict options record partial measured+  | recordCompiler record /= compiler =+      [ "The record was made with "+          <> (if T.null made then "no compiler" else made)+          <> " and these benchmarks were built with "+          <> compiler+          <> ", which allocates differently."+      ]+  | otherwise =+      [ "The costs marked with ! moved further than the tolerances allow."+      | or (judged <> totals)+      ]+        <> [ "The benchmarks marked (new) are not in the record."+           | any ((`Map.notMember` recordEntries record) . fst) measured+           ]+        <> [ "In the record but not measured: " <> group <> " " <> name+           | not partial,+             k@(Key group name) <- Map.keys (recordEntries record),+             k `notElem` fmap fst measured+           ]+  where+    made = recordCompiler record+    judged =+      [ beyond (optTolerance options) cost [(e, m)]+      | (k, m) <- measured,+        Just e <- [Map.lookup k (recordEntries record)],+        cost <- [allocations, instructions]+      ]+    totals =+      [ beyond (optGroupTolerance options) cost (known record group measured)+      | group <- groupsOf measured,+        cost <- [allocations, instructions]+      ]+    beyond tolerance cost =+      maybe False (uncurry (moved tolerance)) . summed cost++-- | Has a cost moved further than a fraction of what it was?+moved :: Double -> Word64 -> Word64 -> Bool+moved tolerance old new =+  abs (fromIntegral new - fromIntegral old)+    > tolerance * (fromIntegral old :: Double)++-- | What to record for a benchmark: each cost as the record has it where it+-- moved no further than two runs of one build differ, so that writing the+-- record again changes only what moved.+steadied :: Maybe Entry -> Entry -> Entry+steadied recorded new = case recorded of+  Nothing -> new+  Just old ->+    Entry+      { entryAllocated = held (entryAllocated old) (entryAllocated new),+        entryInstructions =+          (held <$> entryInstructions old <*> entryInstructions new)+            <|> entryInstructions new+      }+  where+    held o n = if moved jitter o n then n else o++-- | How far a cost moves between two runs of one build, as a fraction.+jitter :: Double+jitter = 0.0001++-- | The groups measured, in the order they were.+groupsOf :: [(Key, Measurement)] -> [Text]+groupsOf measured = nubOrd [group | (Key group _, _) <- measured]++-- | What the record and the measurements say about each benchmark of a+-- group that both have.+known :: Record -> Text -> [(Key, Measurement)] -> [(Entry, Measurement)]+known record group measured =+  [ (e, m)+  | (k@(Key g _), m) <- measured,+    g == group,+    Just e <- [Map.lookup k (recordEntries record)]+  ]++-- | What an earlier run measured: the time of every benchmark and the+-- instructions it retired, where they were counted.+type Baseline = Map Key (Int64, Maybe Word64)++-- | Save what was measured.+writeBaseline :: FilePath -> [(Key, Measurement)] -> IO ()+writeBaseline path measured =+  T.writeFile path . T.unlines $+    [ T.unwords+        [ group,+          T.pack (show (measuredTime m)),+          maybe "-" (T.pack . show) (measuredInstructions m),+          name+        ]+    | (Key group name, m) <- measured+    ]++-- | Read what 'writeBaseline' saved.+readBaseline :: FilePath -> IO Baseline+readBaseline path = do+  text <- T.readFile path+  pure $+    Map.fromList+      [ (Key group (T.unwords rest), (t, readMaybe (T.unpack retired)))+      | group : time : retired : rest@(_ : _) <- T.words <$> T.lines text,+        Just t <- [readMaybe (T.unpack time)]+      ]++-- | Say how the benchmarks measured on both sides moved against the+-- baseline, all together and where they moved most: by the instructions+-- they retired where both sides counted them, by time otherwise.+summarize :: (Text -> IO ()) -> [(Key, Measurement)] -> Baseline -> IO ()+summarize say measured baseline =+  unless (null both) $ do+    say ""+    say . T.pack $+      printf "Against the baseline, over %d benchmarks:" (length both)+    say . T.pack $+      printf+        "  time %s -> %s %s"+        (duration oldTime)+        (duration newTime)+        (oldTime `against` newTime)+    for_ counted $ \retired ->+      let old = sum (fmap fst retired)+          new = sum (fmap snd retired)+       in say . T.pack $+            printf+              "  instructions %s -> %s %s"+              (count old)+              (count new)+              (old `against` new)+    for_ (take 5 (sortOn (Down . abs . snd) movers)) $ \(Key group name, c) ->+      say (T.pack (printf "  (%+.2f%%) %s %s" c group name))+  where+    both =+      [ (k, ((t, i), (measuredTime m, measuredInstructions m)))+      | (k, m) <- measured,+        Just (t, i) <- [Map.lookup k baseline]+      ]+    oldTime = sum [t | (_, ((t, _), _)) <- both]+    newTime = sum [t | (_, (_, (t, _))) <- both]+    counted =+      traverse (\(_, ((_, old), (_, new))) -> (,) <$> old <*> new) both+    movers = case counted of+      Just retired ->+        zip (fmap fst both) [change' old new | (old, new) <- retired]+      Nothing ->+        [(k, change' old new) | (k, ((old, _), (new, _))) <- both]+    change' :: Integral a => a -> a -> Double+    change' old new = change (fromIntegral old) (fromIntegral new)++-- | How much a quantity moved from the first value to the second, as the+-- report writes it.+against :: Integral a => a -> a -> String+against old new =+  printf "(%+.2f%%)" (change (fromIntegral old) (fromIntegral new))++-- | How much a quantity moved, in percent.+change :: Double -> Double -> Double+change old new+  | old == 0 = 0+  | otherwise = 100 * (new - old) / old++-- | Instructions, or as much space where they were not counted.+instructionsColumn :: Maybe Word64 -> String+instructionsColumn = maybe (replicate 13 ' ') (printf "%13s" . count)++-- | Nanoseconds, in the unit that suits them.+duration :: Int64 -> String+duration = scaled ["ns", "μs", "ms", "s"] . fromIntegral++-- | Bytes, in the unit that suits them.+bytes :: Word64 -> String+bytes = scaled ["B", "kB", "MB", "GB", "TB"] . fromIntegral++-- | A count of instructions, in the unit that suits it.+count :: Word64 -> String+count =+  scaled ["instr", "k instr", "M instr", "G instr", "T instr"]+    . fromIntegral++-- | A quantity to four significant digits, in the first of the units, each+-- a thousand times the one before, that keeps it under a thousand.+scaled :: [String] -> Double -> String+scaled units x = case units of+  [] -> number x+  [u] -> number x <> " " <> u+  u : us+    | x >= 999.95 -> scaled us (x / 1000)+    | otherwise -> number x <> " " <> u+  where+    number :: Double -> String+    number v+      | v < 9.9995 = printf "%.3f" v+      | v < 99.995 = printf "%.2f" v+      | otherwise = printf "%.1f" v
+ tests/Main.hs view
@@ -0,0 +1,241 @@+{-# LANGUAGE OverloadedStrings #-}++module Main (main) where++import Control.Exception (evaluate)+import Data.Either (isLeft)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List (isInfixOf)+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text qualified as T+import Data.Version (showVersion)+import System.FilePath ((</>))+import System.IO.Temp (withSystemTempDirectory)+import System.Info (fullCompilerVersion)+import Test.Hspec++import Lynceus+import Lynceus.Benchmark+import Lynceus.Measure+import Lynceus.Options+import Lynceus.Record+import Lynceus.Run++main :: IO ()+main = hspec $ do+  describe "parseRecord" $ do+    it "reads what renderRecord writes" $+      parseRecord (renderRecord sample) `shouldBe` sample+    it "reads a record whose lines end in CRLF" $+      parseRecord (T.replace "\n" "\r\n" (renderRecord sample))+        `shouldBe` sample+    it "ignores comments and blank lines" $+      recordEntries (parseRecord "# a 1 2 b\n\ngroup 1 - name\n")+        `shouldBe` Map.singleton (Key "group" "name") (Entry 1 Nothing)+  describe "readRecord" $+    it "reads a missing record as an empty one" $+      withSystemTempDirectory "lynceus" $ \dir ->+        readRecord (dir </> "missing") `shouldReturn` emptyRecord+  describe "validate" $ do+    it "accepts single-word groups and benchmarks named by words" $+      validate [group "parse" [bench "a module" work, bench "b" work]]+        `shouldBe` []+    it "rejects a group not named by a single word" $+      validate [group "two words" []]+        `shouldBe` [InvalidGroupName "two words"]+    it "rejects a group named by a reserved word" $+      validate [group "compiler" []] `shouldBe` [ReservedGroupName "compiler"]+    it "rejects a group named like a comment" $+      validate [group "#group" []] `shouldBe` [ReservedGroupName "#group"]+    it "rejects a group named twice" $+      validate [group "g" [], group "g" []] `shouldBe` [DuplicateGroupName "g"]+    it "rejects benchmarks named by anything but words" $+      validate [group "g" [bench "" work, bench " a" work, bench "a  b" work]]+        `shouldBe` [ InvalidBenchName "g" "",+                     InvalidBenchName "g" " a",+                     InvalidBenchName "g" "a  b"+                   ]+    it "rejects a benchmark named twice in one group" $+      validate [group "g" [bench "a" work, bench "a" work]]+        `shouldBe` [DuplicateBenchName "g" "a"]+  describe "parseArguments" $ do+    it "gives the options given for no arguments" $+      parseArguments defaultOptions [] `shouldBe` Right (Just defaultOptions)+    it "sets the arguments on top of the options given" $ do+      let given = defaultOptions{optRuns = 3}+      parseArguments given ["--tolerance", "1"]+        `shouldBe` Right (Just given{optTolerance = 0.01})+    it "gives nothing where help is asked for" $+      parseArguments defaultOptions ["--help"] `shouldBe` Right Nothing+    it "reads tolerances as percentages" $+      fmap optTolerance <$> parseArguments defaultOptions ["--tolerance", "1"]+        `shouldBe` Right (Just 0.01)+    it "rejects a run count that is not positive" $+      parseArguments defaultOptions ["--runs", "0"] `shouldSatisfy` isLeft+    it "rejects arguments that are not options" $+      parseArguments defaultOptions ["extra"] `shouldSatisfy` isLeft+  describe "usage" $+    it "gives the options given as the defaults" $ do+      usage defaultOptions `shouldSatisfy` isInfixOf "(default: 0.5)"+      usage defaultOptions `shouldSatisfy` isInfixOf "(default: 0.05)"+      usage defaultOptions{optTolerance = 0.012}+        `shouldSatisfy` isInfixOf "(default: 1.2)"+  describe "steadied" $ do+    it "keeps what moved no further than runs differ" $+      steadied (Just (Entry 100000 (Just 100000))) (Entry 100001 (Just 99999))+        `shouldBe` Entry 100000 (Just 100000)+    it "takes what moved further" $+      steadied (Just (Entry 100 (Just 100))) (Entry 101 (Just 99))+        `shouldBe` Entry 101 (Just 99)+    it "takes instructions the record does not have" $+      steadied (Just (Entry 100 Nothing)) (Entry 100 (Just 7))+        `shouldBe` Entry 100 (Just 7)+  describe "verdict" $ do+    let judged partial ms =+          verdict+            defaultOptions+            ( recordOf+                [(Key "format" "Foo", 100000), (Key "format" "Bar", 200000)]+            )+            partial+            (fmap measured <$> ms)+    it "finds nothing wrong within the tolerances" $+      judged False [(Key "format" "Foo", 100000), (Key "format" "Bar", 200000)]+        `shouldBe` []+    it "finds a benchmark that moved too far" $+      judged False [(Key "format" "Foo", 101000), (Key "format" "Bar", 200000)]+        `shouldBe` [moved]+    it "finds a group that moved too far together" $+      judged False [(Key "format" "Foo", 100300), (Key "format" "Bar", 199500)]+        `shouldBe` [moved]+    it "finds a benchmark not in the record" $+      judged True [(Key "format" "Qux", 1)]+        `shouldBe` ["The benchmarks marked (new) are not in the record."]+    it "finds a benchmark not measured, unless only some were" $ do+      judged False [(Key "format" "Foo", 100000)]+        `shouldBe` ["In the record but not measured: format Bar"]+      judged True [(Key "format" "Foo", 100000)] `shouldBe` []+    it "finds a record made with another compiler" $+      verdict defaultOptions sample False []+        `shouldSatisfy` ((== 1) . length)+  describe "measure" $ do+    it "measures the same allocations on every run" $ do+      m <- measure Nothing 3 (nf (\n -> [1 .. n :: Int]) 1000)+      measuredAllocated m `shouldSatisfy` (> 16000)+      measuredSpread m `shouldBe` 0+    it "evaluates no further than weak head normal form with whnf" $ do+      lazy <- measure Nothing 1 (whnf enum 1000)+      strict <- measure Nothing 3 (whnf (reverse . enum) 1000)+      measuredAllocated lazy `shouldSatisfy` (< 16000)+      measuredAllocated strict `shouldSatisfy` (> 16000)+      measuredSpread strict `shouldBe` 0+    it "runs a setup anew before every run and leaves it unmeasured" $ do+      setups <- newIORef (0 :: Int)+      let setup = do+            modifyIORef' setups (+ 1)+            _ <- evaluate (sum (reverse (enum 100000)))+            pure (pure () :: IO ())+      m <- measure Nothing 3 (withSetupWhnf setup nfIO)+      readIORef setups `shouldReturn` 4+      measuredAllocated m `shouldSatisfy` (< 16000)+  describe "run" $ do+    let loose = defaultOptions{optTolerance = 0.5, optGroupTolerance = 0.5}+        groups =+          [ group+              "lists"+              [bench "short" (nf enum 1000), bench "long" (nf enum 10000)]+          ]+        running options mode path = run options mode (\_ -> pure ()) path+    it "checks what it accepted" $+      withRecord groups $ \path ->+        running loose Check path groups `shouldReturn` True+    it "fails where the record says otherwise" $+      withRecord groups $ \path -> do+        tamper path+        running loose Check path groups `shouldReturn` False+    it "marks the costs that moved too far" $+      withRecord groups $ \path -> do+        tamper path+        said <- newIORef []+        _ <- run loose Check (\l -> modifyIORef' said (l :)) path groups+        lines' <- readIORef said+        filter (\l -> any (`T.isInfixOf` l) ["lists", "short", "long"]) lines'+          `shouldSatisfy` all ("%)!" `T.isInfixOf`)+        lines' `shouldSatisfy` elem moved+    it "fails where a benchmark is not in the record" $+      withRecord groups $ \path ->+        running loose Check path (group "new" [bench "a" work] : groups)+          `shouldReturn` False+    it "checks only the benchmarks that match" $+      withRecord groups $ \path ->+        running+          loose{optMatch = Just "short"}+          Check+          path+          (group "new" [bench "a" work] : groups)+          `shouldReturn` True++-- | A record of two benchmarks of one group and one of another.+sample :: Record+sample =+  Record+    { recordCompiler = "ghc 0.0",+      recordProcessor = "none",+      recordEntries =+        Map.fromList+          [ (Key "format" "Foo", Entry 100 Nothing),+            (Key "format" "Bar baz", Entry 200 Nothing),+            (Key "parse" "Foo", Entry 300 (Just 400))+          ]+    }++-- | A record made with the compiler of the tests of what the given+-- benchmarks allocated.+recordOf :: [(Key, Int)] -> Record+recordOf entries =+  emptyRecord+    { recordCompiler = compiler,+      recordEntries =+        Map.fromList [(k, Entry (fromIntegral a) Nothing) | (k, a) <- entries]+    }++-- | What the verdict says where costs moved too far.+moved :: Text+moved = "The costs marked with ! moved further than the tolerances allow."++-- | What a benchmark allocated, with nothing else measured.+measured :: Int -> Measurement+measured allocated = Measurement (fromIntegral allocated) Nothing 0 0++-- | The compiler the tests were built with, as the record names it.+compiler :: Text+compiler = T.pack ("ghc " <> showVersion fullCompilerVersion)++-- | Some work.+work :: Work+work = nf enum 10++-- | A list of numbers up to the given one.+enum :: Int -> [Int]+enum n = [1 .. n]++-- | Run an action with a record accepted for the given benchmarks.+withRecord :: [Group] -> (FilePath -> IO ()) -> IO ()+withRecord groups action =+  withSystemTempDirectory "lynceus" $ \dir -> do+    let path = dir </> "bench.record"+    run defaultOptions Accept (\_ -> pure ()) path groups `shouldReturn` True+    action path++-- | Make every benchmark of a record allocate ten times as much.+tamper :: FilePath -> IO ()+tamper path = do+  record <- readRecord path+  writeRecord+    path+    record+      { recordEntries =+          (\e -> e{entryAllocated = 10 * entryAllocated e})+            <$> recordEntries record+      }