0cd9333caa59df50d0a1c856c48d2f5054609e08
[ghc-hetmet.git] / ghc / lib / std / CPUTime.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1995-1997
3 %
4 \section[CPUTime]{Haskell 1.4 CPU Time Library}
5
6 \begin{code}
7 {-# OPTIONS -#include "cbits/stgio.h" #-}
8
9 module CPUTime 
10         (
11          getCPUTime,       -- :: IO Integer
12          cpuTimePrecision  -- :: Integer
13         ) where
14 \end{code}
15
16
17 #ifndef __HUGS__
18
19 \begin{code}
20 import Prelude          -- To generate the dependency
21 import PrelGHC          ( indexIntArray# )
22 import PrelBase         ( Int(..) )
23 import PrelByteArr      ( ByteArray(..), newIntArray )
24 import PrelArrExtra     ( unsafeFreezeByteArray )
25 import PrelNum          ( fromInt )
26 import PrelIOBase       ( IOError(..), IOErrorType( UnsupportedOperation ), 
27                           unsafePerformIO, stToIO )
28 import Ratio
29 \end{code}
30
31 Computation @getCPUTime@ returns the number of picoseconds CPU time
32 used by the current program.  The precision of this result is
33 implementation-dependent.
34
35 The @cpuTimePrecision@ constant is the smallest measurable difference
36 in CPU time that the implementation can record, and is given as an
37 integral number of picoseconds.
38
39 \begin{code}
40 getCPUTime :: IO Integer
41 getCPUTime = do
42     marr <- stToIO (newIntArray ((0::Int),3))
43     barr <- stToIO (unsafeFreezeByteArray marr)
44     rc   <- primGetCPUTime barr
45     if rc /= 0 then
46       case barr of
47        ByteArray _ _ frozen# -> -- avoid bounds checking
48         return ((fromIntegral (I# (indexIntArray# frozen# 0#)) * 1000000000 + 
49                  fromIntegral (I# (indexIntArray# frozen# 1#)) + 
50                  fromIntegral (I# (indexIntArray# frozen# 2#)) * 1000000000 + 
51                  fromIntegral (I# (indexIntArray# frozen# 3#))) * 1000)
52      else
53         ioError (IOError Nothing UnsupportedOperation 
54                          "getCPUTime"
55                          "can't get CPU time")
56
57 cpuTimePrecision :: Integer
58 cpuTimePrecision = round ((1000000000000::Integer) % 
59                           fromInt (unsafePerformIO clockTicks))
60
61 foreign import "libHS_cbits" "getCPUTime" unsafe primGetCPUTime :: ByteArray Int -> IO Int
62 foreign import "libHS_cbits" "clockTicks" clockTicks :: IO Int
63
64 \end{code}
65
66 #else
67
68 \begin{code}
69 import PrelPrim ( nh_getCPUtime
70                 , nh_getCPUprec
71                 , unsafePerformIO
72                 )
73
74 getCPUTime :: IO Integer
75 getCPUTime 
76    = do seconds <- nh_getCPUtime
77         return (round (seconds * 1.0e+12))
78
79 cpuTimePrecision :: Integer
80 cpuTimePrecision
81    = unsafePerformIO (
82         do resolution <- nh_getCPUprec
83            return (round (resolution * 1.0e+12))
84      )
85 \end{code} 
86 #endif