Ticket #4004: Benchmark.hs

File Benchmark.hs, 1.5 KB (added by rtvd, 3 years ago)

Benchmark I used to tune the performance.

Line 
1{-# LANGUAGE ForeignFunctionInterface, MagicHash, UnboxedTuples, BangPatterns #-}
2
3module Main (
4  main
5) where
6
7import Foreign.Ptr
8import Foreign.Storable
9import Foreign.C.Types
10import Foreign.C.String
11import Foreign.ForeignPtr
12import Foreign.Marshal.Alloc
13import Foreign.Marshal.Array
14import Foreign.Marshal.Utils
15import Data.Time.Clock.POSIX
16import Control.Monad
17import Control.Concurrent.MVar
18import qualified Data.ByteString.Char8 as BS
19
20benchmarkIt (name, task) = do
21  t1 <- getPOSIXTime
22  sequence_ $ replicate 1000000000 task
23  t2 <- getPOSIXTime
24  putStrLn $ name ++ ": " ++  show ((fromIntegral $ round ((t2 - t1)*1000))*1e-3) ++ " ns"
25
26main =
27  mapM_ benchmarkIt [
28    ("withCString", withCString "abracadabra" $ ((\ptr -> return ()) :: CString -> IO () )),
29    ("alloca", alloca $ ((\ptr -> return ()) :: Ptr Int -> IO ())),
30    ("allocaBytes", allocaBytes 40 $ ((\ptr -> return ()) :: Ptr Int -> IO ())),
31    ("mallocForeignPointer", (mallocForeignPtr :: IO (ForeignPtr Int)) >> return () ),
32    ("bytestring", (BS.useAsCStringLen (BS.pack "abracadabra")) (\cstr -> BS.packCStringLen cstr >> return ()) ),
33    ("mvar", do
34      mv <- newEmptyMVar
35      putMVar mv 12345
36      modifyMVar_ mv $! (\v -> return $! v+1)
37      takeMVar mv
38      return ()
39      ),
40    ("alloca+advancePtr", alloca $ \ptr -> let ptr' = advancePtr ptr 3 in if ptr' == (nullPtr::Ptr Int) then fail "miserably" else return ()),
41    ("new/finalizerFree", new (12345::CLong) >>= free),
42    ("with", with 'c' $ \ptr -> return ())
43  ]