{-# LINE 1 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
{-# LANGUAGE CPP, CApiFFI, NumDecimals #-}




module System.CPUTime.Posix.RUsage
    ( getCPUTime
    , getCpuTimePrecision
    ) where

import Data.Ratio
import Foreign
import Foreign.C
import System.CPUTime.Utils

-- For struct rusage

{-# LINE 18 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}


{-# LINE 20 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}


{-# LINE 22 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}

getCPUTime :: IO Integer
getCPUTime :: IO Integer
getCPUTime = Int -> (Ptr CRUsage -> IO Integer) -> IO Integer
forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes (Int
144) ((Ptr CRUsage -> IO Integer) -> IO Integer)
-> (Ptr CRUsage -> IO Integer) -> IO Integer
forall a b. (a -> b) -> a -> b
$ \ Ptr CRUsage
p_rusage -> do
{-# LINE 25 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    throwErrnoIfMinus1_ "getrusage" $ getrusage (0) p_rusage
{-# LINE 26 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}

    let ru_utime = ((\hsc_ptr -> hsc_ptr `plusPtr` 0)) p_rusage
{-# LINE 28 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    let ru_stime = ((\hsc_ptr -> hsc_ptr `plusPtr` 16)) p_rusage
{-# LINE 29 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    u_sec  <- ((\hsc_ptr -> peekByteOff hsc_ptr 0))  ru_utime :: IO CTime
{-# LINE 30 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    u_usec <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ru_utime :: IO CSUSeconds
{-# LINE 31 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    s_sec  <- ((\hsc_ptr -> peekByteOff hsc_ptr 0))  ru_stime :: IO CTime
{-# LINE 32 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    s_usec <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ru_stime :: IO CSUSeconds
{-# LINE 33 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}
    let usec = cTimeToInteger u_sec * 1e6 + csuSecondsToInteger u_usec +
               cTimeToInteger s_sec * 1e6 + csuSecondsToInteger s_usec
    return (usec * 1e6)

type CRUsage = ()
foreign import capi unsafe "HsBase.h getrusage" getrusage :: CInt -> Ptr CRUsage -> IO CInt

getCpuTimePrecision :: IO Integer
getCpuTimePrecision :: IO Integer
getCpuTimePrecision =
    Integer -> IO Integer
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Integer -> IO Integer) -> Integer -> IO Integer
forall a b. (a -> b) -> a -> b
$ Ratio Integer -> Integer
forall b. Integral b => Ratio Integer -> b
forall a b. (RealFrac a, Integral b) => a -> b
round ((Integer
1e12::Integer) Integer -> Integer -> Ratio Integer
forall a. Integral a => a -> a -> Ratio a
% CLong -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral CLong
clk_tck)

foreign import ccall unsafe clk_tck :: CLong


{-# LINE 55 "libraries/base/System/CPUTime/Posix/RUsage.hsc" #-}