[project @ 2000-03-28 08:52:28 by simonmar]
[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 Prelude
70 import privileged Prelude ( nh_getCPUtime
71                           , nh_getCPUprec
72                           , unsafePerformIO
73                           )
74
75 getCPUTime :: IO Integer
76 getCPUTime 
77    = do seconds <- nh_getCPUtime
78         return (round (seconds * 1.0e+12))
79
80 cpuTimePrecision :: Integer
81 cpuTimePrecision
82    = unsafePerformIO (
83         do resolution <- nh_getCPUprec
84            return (round (resolution * 1.0e+12))
85      )
86 \end{code} 
87 #endif