@@ -311,6 +311,7 @@ module Streamly.Internal.Data.Stream.StreamD
311311 -- * Time related
312312 , takeByTime
313313 , dropByTime
314+ , currentTime
314315 )
315316where
316317
@@ -345,6 +346,7 @@ import qualified Control.Monad.Reader as Reader
345346import qualified Control.Monad.State.Strict as State
346347import qualified Prelude
347348
349+import Data.Int (Int64)
348350import Streamly.Internal.Mutable.Prim.Var
349351 (Prim, Var, readVar, newVar, modifyVar')
350352import Streamly.Internal.Data.Time.Units
@@ -355,6 +357,7 @@ import Streamly.Internal.Memory.Array.Types (Array(..))
355357import Streamly.Internal.Data.Fold.Types (Fold(..))
356358import Streamly.Internal.Data.Pipe.Types (Pipe(..), PipeState(..))
357359import Streamly.Internal.Data.Time.Clock (Clock(Monotonic), getTime)
360+import Streamly.Internal.Data.Time.Units (MicroSecond64(..), fromAbsTime, toAbsTime, AbsTime)
358361import Streamly.Internal.Data.Unfold.Types (Unfold(..))
359362import Streamly.Internal.Data.Strict (Tuple3'(..))
360363
@@ -4207,3 +4210,26 @@ dropByTime duration (Stream step1 state1) = Stream step (DropByTimeInit state1)
42074210 Yield x s -> Yield x (DropByTimeYield s)
42084211 Skip s -> Skip (DropByTimeYield s)
42094212 Stop -> Stop
4213+
4214+{-# INLINE_NORMAL currentTime #-}
4215+currentTime :: MonadAsync m => Double -> Stream m AbsTime
4216+currentTime g = Stream step Nothing
4217+ where
4218+ next timeVar = do
4219+ threadDelay $ delayTime
4220+ MicroSecond64 t <- fromAbsTime <$> getTime Monotonic
4221+ modifyVar' timeVar (const t)
4222+ next timeVar
4223+ g' = g * 10 ^ (6 :: Int)
4224+ {-# INLINE delayTime #-}
4225+ delayTime = if g' >= fromIntegral (maxBound :: Int)
4226+ then maxBound
4227+ else round g'
4228+ {-# INLINE_LATE step #-}
4229+ step _ Nothing = do
4230+ timeVar <- liftIO $ newVar (0 :: Int64)
4231+ tid <- forkManaged $ liftIO $ void $ next timeVar
4232+ return $ Skip $ Just (timeVar, tid)
4233+ step _ s@(Just (timeVar, _)) = do
4234+ a <- liftIO $ readVar timeVar
4235+ return $ Yield (toAbsTime (MicroSecond64 a)) s