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