0aa8e0614f00387bf386274f6394c91be562be63
[ghc-hetmet.git] / ghc / lib / std / cbits / getClockTime.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * $Id: getClockTime.c,v 1.8 1999/10/26 09:34:09 sof Exp $
5  *
6  * getClockTime Runtime Support
7  */
8
9 #ifndef _AIX
10 #define NON_POSIX_SOURCE    /* gettimeofday */
11 #endif
12
13 #include "Rts.h"
14 #include "stgio.h"
15
16 /* Note: skewing this code in favour of non-POSIX calls
17    such as gettimeofday() and getclock() rather than time(),
18    may seem strange/wrong. There's a good reason for it
19    though - the non-POSIX calls gives you better precision --
20    they return usecs (or nsecs) as well as seconds, which
21    the users of getClockTime() is interested in knowing.
22  */
23
24 #if defined(HAVE_GETTIMEOFDAY)
25 #  ifdef HAVE_SYS_TIME_H
26 #   include <sys/time.h>
27 #  endif
28 #elif defined(HAVE_GETCLOCK)
29 # ifdef HAVE_SYS_TIMERS_H
30 #  define POSIX_4D9 1
31 #  include <sys/timers.h>
32 # endif
33 #elif defined(HAVE_TIME_H)
34 # include <time.h>
35 #endif
36
37 #ifdef HAVE_WINDOWS_H
38 #include <windows.h>
39 #include <sys/types.h>
40 #include <sys/timeb.h>
41 #endif
42
43 StgInt
44 getClockTime(StgByteArray sec, StgByteArray nsec)
45 {
46 #if defined(_WIN32) && !defined(cygwin32_TARGET_OS)
47   /*
48    * ftime() as implemented by cygwin (in B20.1) is
49    * not right, so stay away & use time() there instead.
50    */
51   struct timeb t;
52
53   _ftime(&t);
54
55   ((unsigned int *)sec)[0] = (unsigned int)t.time;
56   ((unsigned int *)nsec)[0] = (unsigned int)t.millitm * 1000;
57   return 0;
58 #elif defined(HAVE_GETTIMEOFDAY)
59     struct timeval tp;
60  
61     if (gettimeofday(&tp, NULL) != 0) {
62         cvtErrno();
63         stdErrno();
64         return -1;
65     }
66     ((unsigned long int *)sec)[0] = tp.tv_sec;
67     ((unsigned long int *)nsec)[0] = tp.tv_usec * 1000;
68     return 0;
69 #elif defined(HAVE_GETCLOCK)
70     struct timespec tp;
71
72     if (getclock(TIMEOFDAY, &tp) != 0) {
73         cvtErrno();
74         stdErrno();
75         return -1;
76     }
77     ((unsigned long int *)sec)[0] = tp.tv_sec;
78     ((unsigned long int *)nsec)[0] = tp.tv_nsec;
79     return 0;
80 #elif defined(HAVE_TIME_H)
81     time_t t;
82     if ((t = time(NULL)) == (time_t) -1) {
83         cvtErrno();
84         stdErrno();
85         return -1;
86     }
87     ((unsigned long int *)sec)[0] = t;
88     ((unsigned long int *)nsec)[0] = 0;
89     return 0;
90 #else
91 #error "getClockTime: don't know how to get at the clock's time"
92 #endif
93 }