nano-ui-0.2.0.0: lib/NanoUI/Testing/Harness.hs
-- | Shared helpers for integration tests: input gestures, spans, scroll checks.
module NanoUI.Testing.Harness
( -- * Input gestures
clickPair
, clickPairWith
, rightClickPair
, pressAt
, pressWith
, holdAt
, releaseAt
, releaseWith
, keyInp
, keyRepeatInp
, chordInp
, keyUpInp
, tabInp
, withInputOff
, withDelta
, centerOf
-- * Frame warmup and interaction drivers
, warmup
, warmup2
, warmupDraw
, warmupFocused
, setFocus
, held
, runClick
, runRightClick
, runDragFrom
, clickPos
, clickTab
, dragPos
, dragWindowEdge
, findGrabHover
, cursorOver
-- * Text spans and bounds
, DemoSpan
, spanCenter
, hasText
, spanLabel
, findExact
, findHeader
, findRightmost
, requireSpan
, expectText
, assertSpansHas
, spanYOf
, spanXOf
, spanRect
, spanRectOf
, covers
, clipCovers
, damageCovers
-- * Draw buffer and arena inspection
, Vertex (..)
, vertexColor
, vertUv
, drawnVertices
, indexedVertices
, textureVertices
, drawTriangles
, trianglePicture
, drawQuads
, nodesOfType
-- * Timing, wakes, and benchmarks
, FrameCost (..)
, frameCost
, newWakeSignal
, measureRuns
) where
import Control.Applicative ((<|>))
import Control.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar, tryTakeMVar)
import Control.Monad (filterM, foldM, forM, forM_, replicateM_, unless, void, when)
import Data.Hashable (hash, hashWithSalt)
import Data.IORef (IORef, writeIORef)
import Data.List (maximumBy)
import Data.Map.Strict qualified as M
import Data.Maybe (fromMaybe, isJust, listToMaybe)
import Data.Ord (comparing)
import Data.Text qualified as T
import Data.Word (Word32, Word8)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Ptr (Ptr)
import Foreign.Storable (peekByteOff)
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Stack (HasCallStack)
import GHC.Stats (RTSStats (..), getRTSStats)
import NanoUI
import NanoUI.Backend
import NanoUI.Internal.Context (ctxFocusId, ctxNodeArena, takeWakes)
import NanoUI.Internal.Layout.Arena (arenaCount, getNodeRect, getNodeType, getWidgetId)
import NanoUI.Internal.Types (clamp)
import NanoUI.Shortcut (Shortcut (..))
import NanoUI.Var (peekVar)
import NanoUI.Testing
import NanoUI.Testing.Assert (assert, evalUi, run2Frames, withInput)
import System.Environment (lookupEnv)
import System.Mem (performGC)
import System.Timeout (timeout)
import Text.Printf (printf)
import Text.Read (readMaybe)
-- | Text bounds, text, foreground, background, and clip in logical window coordinates.
type DemoSpan = (Rect, T.Text, Color, Color, Rect)
-- | One vertex of a frame's draw buffer: position, colour, alpha and UV.
data Vertex = Vertex {vX, vY :: Float, vRgb :: (Float, Float, Float), vA, vU, vV :: Float}
deriving (Eq, Show)
-- The vertex at index @i@, read at the buffer's vertex stride.
vertexAt :: Ptr Word8 -> Int -> IO Vertex
vertexAt vp i = Vertex <$> at 0 <*> at 4 <*> ((,,) <$> at 8 <*> at 12 <*> at 16) <*> at 20 <*> at 24 <*> at 28
where
at o = peekByteOff vp (i * vertexSize + o) :: IO Float
-- | A vertex's colour and alpha as a 'Color'.
vertexColor :: Vertex -> Color
vertexColor v = let (r, g, b) = vRgb v in colorRGBA (byte r) (byte g) (byte b) (byte (vA v))
where
byte f = clamp 0 255 (round (f * 255))
-- | Every vertex of a frame, in buffer order. The draw buffers are borrowed:
-- read them before the context's next frame.
drawnVertices :: DrawData -> IO [Vertex]
drawnVertices dd = withForeignPtr (drawVertices dd) $ \vp -> mapM (vertexAt vp) [0 .. drawVertexCount dd - 1]
-- | The vertex each of these index-buffer positions names.
indexedVertices :: DrawData -> [Int] -> IO [Vertex]
indexedVertices dd is =
withForeignPtr (drawVertices dd) $ \vp -> withForeignPtr (drawIndices dd) $ \ip ->
forM is $ \i -> (peekByteOff ip (i * indexSize) :: IO Word32) >>= vertexAt vp . fromIntegral
-- The index-buffer positions a draw command covers.
cmdIndices :: DrawCmd -> [Int]
cmdIndices c = [fromIntegral (cmdIndexOffset c) .. fromIntegral (cmdIndexOffset c + cmdIndexCount c) - 1]
-- | The vertices the commands drawn from texture @tex@ index, in order.
textureVertices :: Int -> DrawData -> IO [Vertex]
textureVertices tex dd =
indexedVertices dd (concat [cmdIndices c | c <- drawCmdElems dd, cmdTextureId c == tex])
-- | Every indexed triangle of a frame.
drawTriangles :: DrawData -> IO [(Vertex, Vertex, Vertex)]
drawTriangles dd = triples <$> indexedVertices dd [0 .. drawIndexCount dd - 1]
where
triples (a : b : c : rest) = (a, b, c) : triples rest
triples _ = []
-- | A frame's draw triangles as a multiset, for comparing the pictures of
-- two frames. Each key hashes a triangle's vertices with the texture and
-- clip of the command that draws it, and maps to how many such triangles
-- the frame draws and the part of their bounding box inside that clip. The
-- draw buffers are borrowed: read them before the context's next frame.
trianglePicture :: DrawData -> IO (M.Map Int (Int, Rect))
trianglePicture dd =
withForeignPtr (drawVertices dd) $ \vp -> withForeignPtr (drawIndices dd) $ \ip ->
foldM (addCmd vp ip) M.empty (drawCmdElems dd)
where
addCmd vp ip acc c = do
let clip = Rect (cmdClipX c) (cmdClipY c) (cmdClipW c) (cmdClipH c)
salt = hash (cmdTextureId c, (cmdClipX c, cmdClipY c, cmdClipW c, cmdClipH c))
start = fromIntegral (cmdIndexOffset c) :: Int
corner t k = (peekByteOff ip ((start + 3 * t + k) * indexSize) :: IO Word32) >>= vertexAt vp . fromIntegral
add m t = do
vs <- mapM (corner t) [0, 1, 2]
let shown = fromMaybe (Rect 0 0 0 0) (rectIntersect (vertexBounds vs) clip)
key = foldl' hashVertex salt vs
pure $! M.insertWith (\(i, r) (j, _) -> (i + j, r)) key (1, shown) m
foldM add acc [0 .. fromIntegral (cmdIndexCount c) `quot` 3 - 1]
hashVertex s v =
let (r, g, b) = vRgb v
in s `hashWithSalt` vX v `hashWithSalt` vY v `hashWithSalt` r `hashWithSalt` g `hashWithSalt` b
`hashWithSalt` vA v `hashWithSalt` vU v `hashWithSalt` vV v
vertexBounds :: [Vertex] -> Rect
vertexBounds vs =
let xs = map vX vs
ys = map vY vs
in Rect (minimum xs) (minimum ys) (maximum xs - minimum xs) (maximum ys - minimum ys)
-- | Decode the quads a frame actually rasterised: one @(rect, color)@ per
-- six-index quad, in draw order. Unlike span and arena queries, this includes
-- widget chrome such as scroller wells and scrollbar lanes. Use only with
-- quad-packed output, such as square-geometry test contexts. Triangle and
-- rounded-shape output is not supported. Commands with counts not divisible by
-- six throw.
drawQuads :: DrawData -> IO [(Rect, Color)]
drawQuads dd = do
forM_ (drawCmdElems dd) $ \c ->
when (cmdIndexCount c `rem` 6 /= 0) $
error ("drawQuads: draw command packs " ++ show (cmdIndexCount c) ++ " indices; not quad-packed")
quads <$> indexedVertices dd (concatMap cmdIndices (drawCmdElems dd))
where
-- Each quad's 6 indices are [a, b, c, a, c, d]; corners are a, b, c, d.
quads vs = case splitAt 6 vs of
(a : b : c : _ : _ : d : _, rest) -> (vertexBounds [a, b, c, d], vertexColor a) : quads rest
_ -> []
-- | Ids and rects of the frame's nodes of one type, in arena order.
nodesOfType :: NodeType -> Context -> IO [(WidgetId, Rect)]
nodesOfType wanted ctx = do
let na = ctxNodeArena ctx
n <- arenaCount na
matching <- filterM (fmap (== wanted) . getNodeType na) [0 .. n - 1]
forM matching $ \i -> (,) <$> getWidgetId na i <*> getNodeRect na i
-- | Midpoint of a logical rectangle, without clipping it.
spanCenter :: Rect -> V2
spanCenter (Rect x y w h) = V2 (x + w / 2) (y + h / 2)
-- | Whether any span contains the text as a substring.
hasText :: T.Text -> [(Rect, T.Text, a, b, c)] -> Bool
hasText needle = any (\(_, txt, _, _, _) -> needle `T.isInfixOf` txt)
-- Blank-glyph markers some span labels carry in front of their text (blanked
-- sort arrows, flags, sort-reserve padding).
dropSpanMarkers :: T.Text -> T.Text
dropSpanMarkers = T.dropWhile (`elem` ['\x01', '\x02', '\x05'])
-- | Trim surrounding whitespace and remove leading internal blank-glyph markers.
spanLabel :: T.Text -> T.Text
spanLabel txt = dropSpanMarkers (T.strip txt)
-- | Centre of the rightmost nontrivial span with an exact normalised label.
-- Returns 'Nothing' when none matches.
findExact :: T.Text -> [DemoSpan] -> Maybe V2
findExact needle spans =
pickRight
[ (x, spanCenter r)
| (r@(Rect x _ w h), txt, _, _, _) <- spans
, w > 1 && h > 1
, spanLabel txt == needle
]
-- | Find a table-header centre: a span that is the needle plus padding, or
-- else the rightmost span labelled exactly the needle ('findExact'). Text
-- that only starts with the needle, such as "Name (asc)", never matches.
-- Current tables draw their sort mark as a style flag, not padding, so their
-- headers come from the 'findExact' fallback, and a view with another label
-- of the same text to the right needs a finder of its own.
findHeader :: T.Text -> [DemoSpan] -> Maybe V2
findHeader needle spans =
let marked =
[ (x, spanCenter r)
| (r@(Rect x _ w h), txt, _, _, _) <- spans
, w > 1 && h > 1
, let raw = dropSpanMarkers txt
, T.strip raw == needle && T.length raw > T.length needle
]
in pickRight marked <|> findExact needle spans
-- | Centre of the rightmost span containing the substring, or 'Nothing'.
findRightmost :: T.Text -> [DemoSpan] -> Maybe V2
findRightmost needle spans =
pickRight [(x, spanCenter r) | (r@(Rect x _ _ _), txt, _, _, _) <- spans, needle `T.isInfixOf` txt]
pickRight :: [(Float, V2)] -> Maybe V2
pickRight [] = Nothing
-- maximumBy keeps the later of equal elements, so ties choose the rightmost.
pickRight ps = Just (snd (maximumBy (comparing fst) ps))
-- | Return a located point or throw an IO error with the supplied diagnostic.
requireSpan :: String -> Maybe V2 -> IO V2
requireSpan msg = maybe (fail msg) pure
-- | Fail with @msg@ unless a span contains @needle@.
expectText :: String -> T.Text -> [(Rect, T.Text, a, b, c)] -> IO ()
expectText msg needle spans = unless (hasText needle spans) (fail msg)
-- | Press, hold and release at @pos@, then two idle frames.
clickPos :: (Input -> IO ()) -> Input -> V2 -> IO ()
clickPos drawFrame base pos = dragPos drawFrame base pos pos
-- | Locate a named tab from text spans and drive a click. Fails if absent.
clickTab :: (Context -> IO [DemoSpan]) -> (Input -> IO ()) -> Context -> Input -> T.Text -> IO ()
clickTab getSpans drawFrame ctx base name = do
spans <- getSpans ctx
pos <- requireSpan ("selftest: tab " <> T.unpack name) (findExact name spans)
clickPos drawFrame base pos
-- | Press at @from@, hold at @to@ and release there, then two idle frames.
dragPos :: (Input -> IO ()) -> Input -> V2 -> V2 -> IO ()
dragPos drawFrame base from to = do
let press = pressAt base from
hold = holdAt base to
mapM_ drawFrame [press, hold, releaseAt hold, base, base]
-- | 'clickPairWith' 'MouseLeft'.
clickPair :: Input -> V2 -> (Input, Input)
clickPair = clickPairWith MouseLeft
-- | Press and release frames for the button at @pos@, keeping the base
-- input's other fields.
clickPairWith :: MouseButton -> Input -> V2 -> (Input, Input)
clickPairWith b inp pos = let press = pressWith b inp pos in (press, releaseWith b press)
-- | 'clickPairWith' 'MouseRight'.
rightClickPair :: Input -> V2 -> (Input, Input)
rightClickPair = clickPairWith MouseRight
-- | 'pressWith' 'MouseLeft'.
pressAt :: Input -> V2 -> Input
pressAt = pressWith MouseLeft
-- | A frame where the button goes down at @pos@ and is not released.
pressWith :: MouseButton -> Input -> V2 -> Input
pressWith b inp pos =
applyMouseButton b True inp {inputMousePos = pos, inputButtonsReleased = buttonsDelete b (inputButtonsReleased inp)}
-- | The button still down from an earlier 'pressAt', with the pointer at @pos@.
holdAt :: Input -> V2 -> Input
holdAt inp pos = unpress MouseLeft (pressAt inp pos)
-- | 'releaseWith' 'MouseLeft'.
releaseAt :: Input -> Input
releaseAt = releaseWith MouseLeft
-- | A frame where the button comes up at the pointer, with no press.
releaseWith :: MouseButton -> Input -> Input
releaseWith b = applyMouseButton b False . unpress b
unpress :: MouseButton -> Input -> Input
unpress b inp = inp {inputButtonsPressed = buttonsDelete b (inputButtonsPressed inp)}
-- | A frame where the key goes down (not an auto-repeat).
keyInp :: Key -> Input -> Input
keyInp k inp = inp {inputKeys = ks, inputKeysNew = ks}
where
ks = inputKeysFromList [k]
-- | A frame with one auto-repeat of a held key (pressed, but not new).
keyRepeatInp :: Key -> Input -> Input
keyRepeatInp k inp = inp {inputKeys = inputKeysFromList [k], inputKeysNew = mempty}
-- | A frame pressing a chord such as @ctrl <> key \'a\'@, with exactly the
-- chord's modifiers held.
chordInp :: Shortcut -> Input -> Input
chordInp (Shortcut k mods) inp =
(maybe id (`applyKey` True) k inp {inputKeys = mempty, inputKeysNew = mempty}) {inputModifiers = mods}
-- | A frame releasing a key, which drops it from the held keys.
keyUpInp :: Key -> Input -> Input
keyUpInp k inp = applyKey k False inp {inputKeys = mempty, inputKeysNew = mempty, inputKeysReleased = mempty}
-- | Step the tab focus to the next focusable.
tabInp :: Input -> Input
tabInp = keyInp KeyTab
-- | Event-free input with the requested window size and pointer at (-10,-10).
withInputOff :: Float -> Float -> Input
withInputOff w h = (withInput w h) {inputMousePos = V2 (-10) (-10)}
-- | Event-free input with logical width/height and elapsed time in seconds.
withDelta :: Float -> Float -> Float -> Input
withDelta w h dt = (withInput w h) {inputDeltaTime = dt}
-- | Centre of the response rectangle. Warm up the view before using it as a target.
centerOf :: Response -> V2
centerOf = spanCenter . respRect
-- | Run one frame to establish previous geometry. Supply event-free input.
warmup :: Context -> Input -> NanoUI a -> IO ()
warmup ctx inp ui = void (runFrame ctx inp ui)
-- | Run two frames and return the second result, whose responses can use solved
-- geometry from the first. Supply event-free input.
warmup2 :: Context -> Input -> NanoUI a -> IO a
warmup2 ctx inp ui = warmup ctx inp ui >> evalUi ctx inp ui
-- | Two-frame warmup returning the second result and borrowed drawing buffers.
warmupDraw :: Context -> Input -> NanoUI a -> IO (a, DrawData)
warmupDraw ctx inp ui = (\(a, draw, _) -> (a, draw)) <$> run2Frames ctx inp ui
-- | Warm the view up, then Tab onto its first focusable.
warmupFocused :: Context -> Input -> NanoUI a -> IO ()
warmupFocused ctx inp ui = warmup2 ctx inp ui >> void (runFrame ctx (tabInp inp) ui)
-- | Give @wid@ keyboard focus directly, as focus kept from earlier frames
-- does; the next frame sees it.
setFocus :: Context -> WidgetId -> IO ()
setFocus ctx = writeIORef (ctxFocusId ctx)
-- | Run a widget bound to a 'Var' and pair its result with the post-frame
-- 'Var' value. The read uses 'peekVar', so it adds no rerun of its own; a
-- view that reads the 'Var' before the widget mutates it will still rerun,
-- returning the second pass's result without click or change flags.
held :: Var a -> (Var a -> NanoUI r) -> NanoUI (r, a)
held v widget = (,) <$> widget v <*> peekVar v
-- | Per-frame test metrics: view pass count, resulting 'Damage', and number
-- of follow-up idle frames needed until the context is no longer dirty.
data FrameCost = FrameCost
{ fcPasses :: !Int
, fcDamage :: !Damage
, fcFollowUps :: !Int
}
deriving (Eq, Show)
-- | Run one frame of @ui@ with @inp@, counting its view passes, then frames
-- with @idle@ until one returns clean. Fails if eight of them do not settle.
frameCost :: Context -> Input -> Input -> NanoUI a -> IO (a, FrameCost)
frameCost ctx inp idle ui = do
(a, _, dirty) <- runFrame ctx inp ui
dmg <- takeDamage ctx
n <- lastFramePasses ctx
follow <- settle dirty 0
pure (a, FrameCost n dmg follow)
where
settle dirty k
| not dirty = pure k
| k >= (8 :: Int) = fail "frameCost: the view never settled"
| otherwise = do
(_, _, d) <- runFrame ctx idle ui
settle d (k + 1)
runClickWith :: MouseButton -> Context -> Input -> NanoUI a -> V2 -> IO a
runClickWith b ctx inp0 ui pos = let (press, release) = clickPairWith b inp0 pos in warmup ctx press ui >> evalUi ctx release ui
-- | Run a press frame and a release frame at @pos@ ('clickPair'), returning
-- the release frame's result.
runClick :: Context -> Input -> NanoUI a -> V2 -> IO a
runClick = runClickWith MouseLeft
-- | 'runClick' with the right button ('rightClickPair'), as opens a context
-- or edit menu.
runRightClick :: Context -> Input -> NanoUI a -> V2 -> IO a
runRightClick = runClickWith MouseRight
-- | Count a failure unless some span contains the substring.
assertSpansHas :: HasCallStack => IORef Int -> T.Text -> [(Rect, T.Text, a, b, c)] -> IO ()
assertSpansHas failed needle spans = assert failed (hasText needle spans)
matchingRects :: (T.Text -> Bool) -> [(Rect, T.Text, a, b, c)] -> [Rect]
matchingRects p spans = [r | (r, txt, _, _, _) <- spans, p txt]
-- | The rect of the first span whose text contains @needle@.
spanRect :: T.Text -> [(Rect, T.Text, a, b, c)] -> Maybe Rect
spanRect needle = listToMaybe . matchingRects (needle `T.isInfixOf`)
-- | The rect of the first span whose text is exactly @lbl@.
spanRectOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> Maybe Rect
spanRectOf lbl = listToMaybe . matchingRects (== lbl)
-- | Whether the first rect contains the second.
covers :: Rect -> Rect -> Bool
covers (Rect cx cy cw ch) (Rect x y w h) =
cx <= x && cy <= y && cx + cw >= x + w && cy + ch >= y + h
-- | Whether a frame's damage was a clip, and one that covers @rect@.
clipCovers :: Damage -> Rect -> Bool
clipCovers (DamageClip clip) rect = covers clip rect
clipCovers DamageFull _ = False
-- | Whether a frame's damage covers @rect@, the whole window included.
damageCovers :: Damage -> Rect -> Bool
damageCovers DamageFull _ = True
damageCovers dmg rect = clipCovers dmg rect
-- | Y origins of spans whose unmodified text exactly matches the label.
spanYOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> [Float]
spanYOf lbl = map rectY . matchingRects (== lbl)
-- | X origins of spans whose unmodified text exactly matches the label.
spanXOf :: T.Text -> [(Rect, T.Text, a, b, c)] -> [Float]
spanXOf lbl = map rectX . matchingRects (== lbl)
-- | Run a frame with the pointer at @pos@ and return the resulting 'UiCursorKind'.
cursorOver :: Context -> Input -> NanoUI a -> V2 -> IO UiCursorKind
cursorOver ctx inp ui pos = do
let hover = inp {inputMousePos = pos}
_ <- runFrame ctx hover ui
uiCursorKind ctx hover
-- | Probe candidate y positions at a fixed x, running a frame for each, and
-- return the first input that produces a grab cursor.
findGrabHover ::
Context -> NanoUI a -> Input -> Float -> [Float] -> IO (Maybe Input)
findGrabHover ctx ui inp0 thumbX = go
where
go [] = pure Nothing
go (y : ys) = do
kind <- cursorOver ctx inp0 ui (V2 thumbX y)
if kind == UiCursorGrab then pure (Just inp0 {inputMousePos = V2 thumbX y}) else go ys
-- | Press and move a resize handle, then run two button-up frames. Returns
-- the window's recorded bounds, or 'Nothing' if its node is absent.
dragWindowEdge ::
Context
-> Input
-> NanoUI Response
-> V2
-> V2
-> IO (Maybe Rect)
dragWindowEdge ctx inp0 ui grab dest = do
runDragFrom ctx inp0 ui grab dest
win <- warmup2 ctx (inp0 {inputMousePos = dest}) ui
getPrevRect ctx (respId win)
-- | Read UV coordinates of a zero-based vertex. The index must be below
-- 'drawVertexCount' and the borrowed draw buffers must still be valid.
vertUv :: DrawData -> Int -> IO (Float, Float)
vertUv dd i = withForeignPtr (drawVertices dd) $ \vp -> (\v -> (vU v, vV v)) <$> vertexAt vp i
-- | Run press and held-move frames from one point to another. Leaves the button
-- held; the test supplies the release frame when needed.
runDragFrom :: Context -> Input -> NanoUI a -> V2 -> V2 -> IO ()
runDragFrom ctx inp0 ui grab dest =
forM_ [pressAt inp0 grab, holdAt inp0 dest] $ \inp -> runFrame ctx inp ui
-- | Install a wake action on a headless context and return a wait for it.
-- @wait us@ consumes a wake since the last wait, blocking up to @us@
-- microseconds, and returns whether one arrived. Consuming a wake takes the
-- wakes so far ('takeWakes'), as a session loop does after its wait, so the
-- next one signals again. A frame that requests another also wakes the loop,
-- so drain those with @wait 0@ before starting the background job the test
-- waits on.
newWakeSignal :: Context -> IO (Int -> IO Bool)
newWakeSignal ctx = do
signal <- newEmptyMVar
setWakeLoop ctx (void (tryPutMVar signal ()))
pure $ \us -> do
woke <-
if us <= 0
then isJust <$> tryTakeMVar signal
else isJust <$> timeout us (takeMVar signal)
when woke (takeWakes ctx)
pure woke
-- | Run @action@ @warmups@ times, then time it over @NANO_PROFILE_ITERATIONS@
-- runs (@runs@ when unset) and print its mean wall time and allocation per
-- run under @name@. The clock stops before the second GC, which only brings
-- the allocation counter current. Needs the RTS's statistics (@+RTS -T@).
measureRuns :: Int -> Int -> String -> IO () -> IO ()
measureRuns warmups runs0 name action = do
requested <- lookupEnv "NANO_PROFILE_ITERATIONS"
let runs = max 1 (fromMaybe runs0 (requested >>= readMaybe))
replicateM_ warmups action
performGC
s0 <- getRTSStats
t0 <- getMonotonicTimeNSec
replicateM_ runs action
t1 <- getMonotonicTimeNSec
performGC
s1 <- getRTSStats
let perIter :: Double -> Double
perIter total = total / fromIntegral runs
printf "%-34s : %11.6f ms/frame | %11.3f KB alloc/frame\n" name
(perIter (fromIntegral (t1 - t0) / 1e6))
(perIter (fromIntegral (allocated_bytes s1 - allocated_bytes s0) / 1024))