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




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

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

-- For struct rusage

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


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


{-# LINE 23 "libraries/base/src/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 26 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    throwErrnoIfMinus1_ "getrusage" $ getrusage (0) p_rusage
{-# LINE 27 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}

    let ru_utime = ((\hsc_ptr -> hsc_ptr `plusPtr` 0)) p_rusage
{-# LINE 29 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    let ru_stime = ((\hsc_ptr -> hsc_ptr `plusPtr` 16)) p_rusage
{-# LINE 30 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    u_sec  <- ((\hsc_ptr -> peekByteOff hsc_ptr 0))  ru_utime :: IO CTime
{-# LINE 31 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    u_usec <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ru_utime :: IO CSUSeconds
{-# LINE 32 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    s_sec  <- ((\hsc_ptr -> peekByteOff hsc_ptr 0))  ru_stime :: IO CTime
{-# LINE 33 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}
    s_usec <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ru_stime :: IO CSUSeconds
{-# LINE 34 "libraries/base/src/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 56 "libraries/base/src/System/CPUTime/Posix/RUsage.hsc" #-}