File tree Expand file tree Collapse file tree 3 files changed +31
-1
lines changed
src/Control/Monad/Class/MonadTimer
io-sim/src/Control/Monad/IOSim Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -5,6 +5,7 @@ module Control.Monad.Class.MonadTimer.SI
55 -- * Auxiliary functions
66 , diffTimeToMicrosecondsAsInt
77 , microsecondsAsIntToDiffTime
8+ , roundDiffTimeToMicroseconds
89 -- * Re-exports
910 , DiffTime
1011 , MonadFork
@@ -54,6 +55,16 @@ diffTimeToMicrosecondsAsInt d =
5455microsecondsAsIntToDiffTime :: Int -> DiffTime
5556microsecondsAsIntToDiffTime = (/ 1_000_000 ) . fromIntegral
5657
58+ -- | Round to microseconds.
59+ --
60+ roundDiffTimeToMicroseconds :: DiffTime -> DiffTime
61+ roundDiffTimeToMicroseconds d = fromIntegral usec / 1_000_000
62+ where
63+ -- microseconds
64+ usec :: Integer
65+ usec = diffTimeToPicoseconds d `div` 1_000_000
66+
67+
5768class ( MonadTimer. MonadDelay m
5869 , MonadMonotonicTime m
5970 ) => MonadDelay m where
Original file line number Diff line number Diff line change @@ -17,6 +17,8 @@ tests =
1717 prop_diffTimeToMicrosecondsAsIntLeftInverse
1818 , testProperty " diffTimeToMicroseconds right inverse"
1919 prop_diffTimeToMicrosecondsAsIntRightInverse
20+ , testProperty " roundToMicroseconds"
21+ prop_roundDiffTimeToMicroseconds
2022 ]
2123
2224newtype IntDistr = IntDistr Int
@@ -88,3 +90,19 @@ prop_diffTimeToMicrosecondsAsIntRightInverse (DiffTimeDistr a) =
8890 -> " large"
8991 | otherwise
9092 -> " average"
93+
94+
95+ prop_roundDiffTimeToMicroseconds :: DiffTimeDistr -> Property
96+ prop_roundDiffTimeToMicroseconds (DiffTimeDistr d) =
97+ -- rounded is less or equal to d
98+ d' <= d
99+ .&&.
100+ -- difference is less than 1 microsecond
101+ abs (d - d') < 0.000_001
102+ .&&.
103+ -- rounded has no fractional microseconds
104+ case properFraction (d' * 1_000_000 ) of
105+ (_ :: Integer , f ) -> f === 0
106+ where
107+ d' = roundDiffTimeToMicroseconds d
108+
Original file line number Diff line number Diff line change @@ -725,7 +725,8 @@ instance MonadDelay (IOSim s) where
725725
726726instance SI. MonadDelay (IOSim s ) where
727727 threadDelay d =
728- IOSim $ oneShot $ \ k -> ThreadDelay d (k () )
728+ IOSim $ oneShot $ \ k -> ThreadDelay (SI. roundDiffTimeToMicroseconds d)
729+ (k () )
729730
730731data Timeout s = Timeout ! (TVar s TimeoutState ) ! TimeoutId
731732 -- ^ a timeout
You can’t perform that action at this time.
0 commit comments