packages feed

lynceus-0.0.1.0: src/Lynceus/Measure.hs

{-# 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
        )