on 42df609 help sign in
65 lines 2.3 kB history raw
1-- |
2-- Module : Streamly.Time
3-- Copyright : (c) 2017 Harendra Kumar
4--
5-- License : BSD3
6-- Maintainer : harendra.kumar@gmail.com
7-- Stability : experimental
8-- Portability : GHC
9--
10-- Time utilities for reactive programming.
12module Streamly.Time
13 ( periodic
14 , withClock
15 )
16where
18import Control.Monad (when)
19import Control.Concurrent (threadDelay)
21-- | Run an action forever periodically at the given frequency specified in per
22-- second (Hz).
23periodic :: Int -> IO () -> IO ()
24periodic freq action = do
25 action
26 threadDelay (1000000 `div` freq)
27 periodic freq action
29-- | Run a computation on every clock tick, the clock runs at the specified
30-- frequency. It allows running a computation at high frequency efficiently by
31-- maintaining a local clock and adjusting it with the provided base clock at
32-- longer intervals. The first argument is a base clock returning some notion
33-- of time in microseconds. The second argument is the frequency in per second
34-- (Hz). The third argument is the action to run, the action is provided the
35-- local time as an argument.
36withClock :: IO Int -> Int -> (Int -> IO ()) -> IO ()
37withClock clock freq action = do
38 t <- clock
39 go t period period t 0
41 where
43 period = 1000000 `div` freq
45 -- Note that localTime is roughly but not exactly equal to (lastAdj + tick
46 -- * n). That is because we do not abruptly adjust the clock skew instead
47 -- we adjust the tick size.
48 go lastAdj delay tick localTime n = do
49 action localTime
50 when (delay > 0) $ threadDelay delay
52 if (n == freq)
53 then do
54 (t, newTick, newDelay) <- adjustClock lastAdj localTime delay
55 go t newDelay newTick (localTime + newTick) 0
56 else go lastAdj delay tick (localTime + tick) (n + 1)
58 -- Adjust the tick size rather than the clock to avoid abrupt changes
59 -- resulting in jittery behavior at the end of every interval.
60 adjustClock lastAdj localTime delay = do
61 baseTime <- clock
62 let newTick = period + (baseTime - localTime) `div` freq
63 lastPeriod = (baseTime - lastAdj) `div` freq
64 newDelay = max 0 (delay + period - lastPeriod)
65 return (baseTime, newTick, newDelay)