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