Skip to content

Instantly share code, notes, and snippets.

@YoEight
Created June 7, 2017 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YoEight/9f231d3277ceea5e4de710a649f1fe2b to your computer and use it in GitHub Desktop.
Save YoEight/9f231d3277ceea5e4de710a649f1fe2b to your computer and use it in GitHub Desktop.
Simple threadsafe stopwatch
--------------------------------------------------------------------------------
-- |
-- Module : Database.EventStore.Internal.Stopwatch
-- Copyright : (C) 2017 Yorick Laupa
-- License : (see the file LICENSE)
--
-- Maintainer : Yorick Laupa <yo.eight@gmail.com>
-- Stability : provisional
-- Portability : non-portable
--
--------------------------------------------------------------------------------
module Database.EventStore.Internal.Stopwatch
( Stopwatch
, newStopwatch
, stopwatchElapsed
) where
--------------------------------------------------------------------------------
import ClassyPrelude
import Data.Time
--------------------------------------------------------------------------------
data Internal =
Internal { _lastTime :: !UTCTime
, _acc :: !NominalDiffTime
}
--------------------------------------------------------------------------------
initInternal :: UTCTime -> Internal
initInternal now = Internal now 0
--------------------------------------------------------------------------------
update :: UTCTime -> Internal -> Internal
update now (Internal before acc) = Internal now acc'
where
acc' = acc + diffUTCTime now before
--------------------------------------------------------------------------------
newtype Stopwatch = Stopwatch (MVar Internal)
--------------------------------------------------------------------------------
newStopwatch :: IO Stopwatch
newStopwatch = fmap Stopwatch . newMVar . initInternal =<< getCurrentTime
--------------------------------------------------------------------------------
stopwatchElapsed :: Stopwatch -> IO NominalDiffTime
stopwatchElapsed (Stopwatch var) =
modifyMVar var $ \prev -> do
now <- getCurrentTime
let next = update now prev
return (next, _acc next)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment