[project @ 1999-12-20 10:34:27 by simonpj]
[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, unsafeFreezeByteArray )
24 import PrelNum          ( fromInt )
25 import PrelIOBase       ( IOError(..), IOErrorType( UnsupportedOperation ), 
26                           unsafePerformIO, stToIO )
27 import Ratio
28 \end{code}
29
30 Computation @getCPUTime@ returns the number of picoseconds CPU time
31 used by the current program.  The precision of this result is
32 implementation-dependent.
33
34 The @cpuTimePrecision@ constant is the smallest measurable difference
35 in CPU time that the implementation can record, and is given as an
36 integral number of picoseconds.
37
38 \begin{code}
39 getCPUTime :: IO Integer
40 getCPUTime = do
41     marr <- stToIO (newIntArray ((0::Int),3))
42     barr <- stToIO (unsafeFreezeByteArray marr)
43     rc   <- primGetCPUTime barr
44     if rc /= 0 then
45       case barr of
46        ByteArray _ _ frozen# -> -- avoid bounds checking
47         return ((fromIntegral (I# (indexIntArray# frozen# 0#)) * 1000000000 + 
48                  fromIntegral (I# (indexIntArray# frozen# 1#)) + 
49                  fromIntegral (I# (indexIntArray# frozen# 2#)) * 1000000000 + 
50                  fromIntegral (I# (indexIntArray# frozen# 3#))) * 1000)
51      else
52         ioError (IOError Nothing UnsupportedOperation 
53                          "getCPUTime"
54                          "can't get CPU time")
55
56 cpuTimePrecision :: Integer
57 cpuTimePrecision = round ((1000000000000::Integer) % 
58                           fromInt (unsafePerformIO clockTicks))
59
60 foreign import "libHS_cbits" "getCPUTime" unsafe primGetCPUTime :: ByteArray Int -> IO Int
61 foreign import "libHS_cbits" "clockTicks" clockTicks :: IO Int
62
63 \end{code}
64
65 #else
66
67 \begin{code}
68 getCPUTime :: IO Integer
69 getCPUTime 
70    = do seconds <- nh_getCPUtime
71         return (round (seconds * 1.0e+12))
72
73 cpuTimePrecision :: Integer
74 cpuTimePrecision
75    = primRunST (
76         do resolution <- nh_getCPUprec
77            return (round (resolution * 1.0e+12))
78      )
79 \end{code} 
80 #endif