lynceus-0.0.1.0: src/Lynceus/Run.hs
{-# 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