T16916.hs 1.21 KB
Newer Older
1 2 3 4
module Main where

import Control.Concurrent
import Foreign.C
5
import GHC.Clock
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import GHC.Event
import System.CPUTime
import System.Posix.Types

foreign import ccall unsafe "socket" c_socket ::
               CInt -> CInt -> CInt -> IO CInt

makeTestSocketFd :: IO Fd
makeTestSocketFd = do
    sockNum <-
        c_socket
            1 -- PF_LOCAL
            2 -- SOCK_DGRAM
            0
    return $ (fromIntegral sockNum :: Fd)

callback :: FdKey -> Event -> IO ()
callback _ _ = return ()

25 26
-- Idle CPU usage with 0 for 0% and 10^12 for 100%
idleCpuUsage :: IO Double
27
idleCpuUsage = do
28
  startTime <- getMonotonicTime
29
  startCPUTime <- getCPUTime
30
  threadDelay 1000000
31
  endCPUTime <- getCPUTime
32 33
  endTime <- getMonotonicTime
  return $ fromIntegral (endCPUTime - startCPUTime) / (endTime - startTime)
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

main :: IO ()
main = do
  (Just eventMgr) <- getSystemEventManager
  fd <- makeTestSocketFd

  noEventUsage <- idleCpuUsage

  registerFd eventMgr callback fd evtRead OneShot
  registerFd eventMgr callback fd evtWrite OneShot

  eventTriggeredUsage <- idleCpuUsage

  -- CPU consumption should roughly be the same when just idling vs
  -- when idling after the event been triggered
49
  print $ eventTriggeredUsage / noEventUsage < 2.0