Ticket #1692: MainWithTiming.hs

File MainWithTiming.hs, 1.8 KB (added by panne, 6 years ago)
Line 
1module Main where
2
3import Foreign
4import Foreign.C
5import Control.Concurrent
6import Graphics.UI.GLUT
7
8main :: IO ()
9main = do
10    (_,[testNo:_,tl]) <- getArgsAndInitialize
11    initialWindowPosition $= Position 0 0
12    initialWindowSize $= Size 400 400
13    mainWindow <- createWindow "TCB - Bug Test"
14   
15    displayCallback $= return ()
16     
17    let tickLength = read tl
18
19    case testNo of
20      '1' -> test1 tickLength
21      '2' -> test2 tickLength
22      '3' -> test3 tickLength
23           
24    mainLoop
25
26test1 tickLength = do
27    addTimerCallback (tickLength * 1) (putTicks 0)
28    addTimerCallback (tickLength * 2) (putTicks 1)
29    addTimerCallback (tickLength * 3) (putTicks 2)
30    addTimerCallback (tickLength * 4) (putTicks 3)
31    addTimerCallback (tickLength * 5) (putTicks 4)
32   
33test2 tickLength = addTimerCallback tickLength (doTick2 tickLength 0)
34
35test3 tickLength = addTimerCallback tickLength (doTick3 tickLength 0)
36
37putTicks t = do usecs <- getUSecs; putStrLn $ "tick: " ++ show t ++ ", " ++ show usecs
38
39doTick2 :: Timeout -> Int -> IO ()
40doTick2 tickLength t = do
41    putTicks t
42    addTimerCallback tickLength (doTick2 tickLength (t + 1))
43   
44doTick3 :: Timeout -> Int -> IO ()
45doTick3 tickLength t = do
46   forkIO (do putTicks t
47              addTimerCallback tickLength (doTick3 tickLength (t + 1)))
48   yield
49           
50getUSecs :: IO Integer
51getUSecs = allocaArray 2 $ \buf -> do
52   result <- gettimeofday buf nullPtr
53   if (result == 0)
54      then do tv_sec  <- peekElemOff buf 0
55              tv_usec <- peekElemOff buf 1
56              return $ fromIntegral tv_sec * 1000000 + fromIntegral tv_usec
57      else error "gettimeofday failed"
58
59-- slight hack, CLong is not really portable
60foreign import ccall unsafe "sys/time.h gettimeofday" gettimeofday :: Ptr CLong -> Ptr () -> IO CInt