Skip to content

Instantly share code, notes, and snippets.

@liyang
Created April 10, 2014 01:07
Show Gist options
  • Save liyang/10334780 to your computer and use it in GitHub Desktop.
Save liyang/10334780 to your computer and use it in GitHub Desktop.
gettimeofday.hsc
{-# LANGUAGE ForeignFunctionInterface #-}
#include <sys/time.h>
module Main where
import Prelude
import Foreign.C.Error (throwErrnoIfMinus1_)
import Foreign.C.Types
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable
getPOSIXTime :: IO (CTime, CSUSeconds)
getPOSIXTime = allocaBytes #{size struct timeval} $ \ ptv -> do
throwErrnoIfMinus1_ "gettimeofday" $ gettimeofday ptv nullPtr
sec <- #{peek struct timeval, tv_sec} ptv :: IO CTime
usec <- #{peek struct timeval, tv_usec} ptv :: IO CSUSeconds
return (sec, usec)
foreign import ccall unsafe "time.h gettimeofday"
gettimeofday :: Ptr () -> Ptr () -> IO CInt
main :: IO ()
main = do
putStrLn $ "CTime: " ++ show (sizeOf (undefined :: CTime))
putStrLn $ "CUSeconds: " ++ show (sizeOf (undefined :: CUSeconds))
putStrLn $ "CSUSeconds: " ++ show (sizeOf (undefined :: CSUSeconds))
putStrLn $ "timeval: " ++ show (#{size struct timeval} :: Int)
putStrLn $ "tv_sec: " ++ show (#{size ((struct timeval *)NULL)->tv_sec} :: Int)
putStrLn $ "tv_usec: " ++ show (#{size ((struct timeval *)NULL)->tv_usec} :: Int)
getPOSIXTime >>= print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment