File: ThreadDelay001.hs

package info (click to toggle)
ghc 9.0.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 177,780 kB
  • sloc: haskell: 494,441; ansic: 70,262; javascript: 9,423; sh: 8,537; python: 2,646; asm: 1,725; makefile: 1,333; xml: 196; cpp: 167; perl: 143; ruby: 84; lisp: 7
file content (44 lines) | stat: -rw-r--r-- 1,188 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
-- Test that threadDelay actually sleeps for (at least) as long as we
-- ask it

-- On windows the resolution of getCurrentTime is far too low to avoid
-- false positives for this test. So we use the internal method from
-- GHC.Event.Windows.Clock instead.

module Main (main) where

import Control.Concurrent
import Control.Monad
import Data.Time
#if defined(mingw32_HOST_OS)
import GHC.Event.Windows.Clock
#endif
main :: IO ()
main = mapM_ delay (0 : take 7 (iterate (*5) 100))

delay :: Int -> IO ()
delay n = do
#if defined(mingw32_HOST_OS)
  !sec_start <- getClock >>= getTime
  threadDelay n
  !sec_end <- getClock >>= getTime

  let diff = sec_end - sec_start
  when (diff * 1000000 < fromIntegral n) $ do
    putStrLn "threadDelay returned early"
    print(sec_start, sec_end, n, diff*1000000)

#else
  tS <- getCurrentTime
  threadDelay n
  tE <- getCurrentTime
  let req = fromIntegral n * 10 ^ (6 :: Int)
      obs = floor (diffUTCTime tE tS * 10 ^ (12 :: Int))
      diff = obs - req
      diff' :: Double
      diff' = fromIntegral diff /  10 ^ (12 :: Int)

  when (obs < req) $ print (tS, tE, req, obs, diff, diff')
#endif