0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[sbcl.git] / src / code / time.lisp
1 ;;;; low-level time functions
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13
14 (defconstant internal-time-units-per-second 100
15   #!+sb-doc
16   "The number of internal time units that fit into a second. See
17   GET-INTERNAL-REAL-TIME and GET-INTERNAL-RUN-TIME.")
18
19 (defconstant micro-seconds-per-internal-time-unit
20   (/ 1000000 internal-time-units-per-second))
21 \f
22 ;;; The base number of seconds for our internal "epoch". We initialize
23 ;;; this to the time of the first call to GET-INTERNAL-REAL-TIME, and
24 ;;; then subtract this out of the result.
25 (defvar *internal-real-time-base-seconds* nil)
26 (declaim (type (or (unsigned-byte 32) null) *internal-real-time-base-seconds*))
27
28 (defun get-internal-real-time ()
29   #!+sb-doc
30   "Return the real time in the internal time format. This is useful for
31   finding elapsed time. See Internal-Time-Units-Per-Second."
32   ;; FIXME: See comment on OPTIMIZE declaration in GET-INTERNAL-RUN-TIME.
33   (declare (optimize (speed 3) (safety 3)))
34   (multiple-value-bind (ignore seconds useconds) (sb!unix:unix-gettimeofday)
35     (declare (ignore ignore) (type (unsigned-byte 32) seconds useconds))
36     (let ((base *internal-real-time-base-seconds*)
37           (uint (truncate useconds
38                           micro-seconds-per-internal-time-unit)))
39       (declare (type (unsigned-byte 32) uint))
40       (cond (base
41              (truly-the (unsigned-byte 32)
42                         (+ (the (unsigned-byte 32)
43                                 (* (the (unsigned-byte 32) (- seconds base))
44                                    internal-time-units-per-second))
45                            uint)))
46             (t
47              (setq *internal-real-time-base-seconds* seconds)
48              uint)))))
49
50 #!-(and sparc svr4)
51 (defun get-internal-run-time ()
52   #!+sb-doc
53   "Return the run time in the internal time format. This is useful for
54   finding CPU usage."
55   (declare (values (unsigned-byte 32)))
56   ;; FIXME: In CMU CL this was (SPEED 3) (SAFETY 0), and perhaps
57   ;; someday it should be again, since overhead here is annoying. But
58   ;; it's even more annoying to worry about this function returning
59   ;; out-of-range values, so while debugging the profiling code,
60   ;; I set it to (SAFETY 3) for now.
61   (declare (optimize (speed 3) (safety 3)))
62   (multiple-value-bind (ignore utime-sec utime-usec stime-sec stime-usec)
63       (sb!unix:unix-fast-getrusage sb!unix:rusage_self)
64     (declare (ignore ignore)
65              (type (unsigned-byte 31) utime-sec stime-sec)
66              ;; (Classic CMU CL had these (MOD 1000000) instead, but
67              ;; at least in Linux 2.2.12, the type doesn't seem to be
68              ;; documented anywhere and the observed behavior is to
69              ;; sometimes return 1000000 exactly.)
70              (type (integer 0 1000000) utime-usec stime-usec))
71     (+ (the (unsigned-byte 32)
72             (* (the (unsigned-byte 32) (+ utime-sec stime-sec))
73                internal-time-units-per-second))
74        (truncate (+ utime-usec stime-usec)
75                  micro-seconds-per-internal-time-unit))))
76
77 #!+(and sparc svr4)
78 (defun get-internal-run-time ()
79   #!+sb-doc
80   "Return the run time in the internal time format. This is useful for
81   finding CPU usage."
82   (declare (values (unsigned-byte 32)))
83   ;; FIXME: See comment on OPTIMIZE declaration in other
84   ;; version of GET-INTERNAL-RUN-TIME.
85   (declare (optimize (speed 3) (safety 3)))
86   (multiple-value-bind (ignore utime stime cutime cstime)
87       (sb!unix:unix-times)
88     (declare (ignore ignore cutime cstime)
89              (type (unsigned-byte 31) utime stime))
90     (the (unsigned-byte 32) (+ utime stime))))
91 \f
92 ;;;; Encode and decode universal times.
93
94 ;;; Returns two values:
95 ;;;  - the minutes west of GMT.
96 ;;;  - T if daylight savings is in effect, NIL if not.
97 (sb!alien:def-alien-routine get-timezone sb!c-call:void
98   (when sb!c-call:long :in)
99   (minutes-west sb!c-call:int :out)
100   (daylight-savings-p sb!alien:boolean :out))
101
102 ;;; Subtract from the returned Internal-Time to get the universal time.
103 ;;; The offset between our time base and the Perq one is 2145 weeks and
104 ;;; five days.
105 (defconstant seconds-in-week (* 60 60 24 7))
106 (defconstant weeks-offset 2145)
107 (defconstant seconds-offset 432000)
108 (defconstant minutes-per-day (* 24 60))
109 (defconstant quarter-days-per-year (1+ (* 365 4)))
110 (defconstant quarter-days-per-century 146097)
111 (defconstant november-17-1858 678882)
112 (defconstant weekday-november-17-1858 2)
113 (defconstant unix-to-universal-time 2208988800)
114
115 (defun get-universal-time ()
116   #!+sb-doc
117   "Returns a single integer for the current time of
118    day in universal time format."
119   (multiple-value-bind (res secs) (sb!unix:unix-gettimeofday)
120     (declare (ignore res))
121     (+ secs unix-to-universal-time)))
122
123 (defun get-decoded-time ()
124   #!+sb-doc
125   "Returns nine values specifying the current time as follows:
126    second, minute, hour, date, month, year, day of week (0 = Monday), T
127    (daylight savings times) or NIL (standard time), and timezone."
128   (decode-universal-time (get-universal-time)))
129
130 (defun decode-universal-time (universal-time &optional time-zone)
131   #!+sb-doc
132   "Converts a universal-time to decoded time format returning the following
133    nine values: second, minute, hour, date, month, year, day of week (0 =
134    Monday), T (daylight savings time) or NIL (standard time), and timezone.
135    Completely ignores daylight-savings-time when time-zone is supplied."
136   (multiple-value-bind (weeks secs)
137       (truncate (+ universal-time seconds-offset)
138                 seconds-in-week)
139     (let* ((weeks (+ weeks weeks-offset))
140            (second NIL)
141            (minute NIL)
142            (hour NIL)
143            (date NIL)
144            (month NIL)
145            (year NIL)
146            (day NIL)
147            (daylight NIL)
148            (timezone (if (null time-zone)
149                          (multiple-value-bind
150                              (ignore minwest dst)
151                              (get-timezone (- universal-time
152                                               unix-to-universal-time))
153                            (declare (ignore ignore))
154                            (setf daylight dst)
155                            minwest)
156                          (* time-zone 60))))
157       (declare (fixnum timezone))
158       (multiple-value-bind (t1 seconds) (truncate secs 60)
159         (setq second seconds)
160         (setq t1 (- t1 timezone))
161         (let* ((tday (if (< t1 0)
162                          (1- (truncate (1+ t1) minutes-per-day))
163                          (truncate t1 minutes-per-day))))
164           (multiple-value-setq (hour minute)
165             (truncate (- t1 (* tday minutes-per-day)) 60))
166           (let* ((t2 (1- (* (+ (* weeks 7) tday november-17-1858) 4)))
167                  (tcent (truncate t2 quarter-days-per-century)))
168             (setq t2 (mod t2 quarter-days-per-century))
169             (setq t2 (+ (- t2 (mod t2 4)) 3))
170             (setq year (+ (* tcent 100) (truncate t2 quarter-days-per-year)))
171             (let ((days-since-mar0 (1+ (truncate (mod t2 quarter-days-per-year)
172                                                  4))))
173               (setq day (mod (+ tday weekday-november-17-1858) 7))
174               (let ((t3 (+ (* days-since-mar0 5) 456)))
175                 (cond ((>= t3 1989)
176                        (setq t3 (- t3 1836))
177                        (setq year (1+ year))))
178                 (multiple-value-setq (month t3) (truncate t3 153))
179                 (setq date (1+ (truncate t3 5))))))))
180       (values second minute hour date month year day
181               daylight
182               (if daylight
183                   (1+ (/ timezone 60))
184                   (/ timezone 60))))))
185
186 (defun pick-obvious-year (year)
187   (declare (type (mod 100) year))
188   (let* ((current-year (nth-value 5 (get-decoded-time)))
189          (guess (+ year (* (truncate (- current-year 50) 100) 100))))
190     (declare (type (integer 1900 9999) current-year guess))
191     (if (> (- current-year guess) 50)
192         (+ guess 100)
193         guess)))
194
195 (defun leap-years-before (year)
196   (let ((years (- year 1901)))
197     (+ (- (truncate years 4)
198           (truncate years 100))
199        (truncate (+ years 300) 400))))
200
201 (defvar *days-before-month*
202   #.(let ((reversed-result nil)
203           (sum 0))
204       (push nil reversed-result)
205       (dolist (days-in-month '(31 28 31 30 31 30 31 31 30 31 30 31))
206         (push sum reversed-result)
207         (incf sum days-in-month))
208       (coerce (nreverse reversed-result) 'simple-vector)))
209
210 (defun encode-universal-time (second minute hour date month year
211                                      &optional time-zone)
212   #!+sb-doc
213   "The time values specified in decoded format are converted to
214    universal time, which is returned."
215   (declare (type (mod 60) second)
216            (type (mod 60) minute)
217            (type (mod 24) hour)
218            (type (integer 1 31) date)
219            (type (integer 1 12) month)
220            (type (or (integer 0 99) (integer 1900)) year)
221            (type (or null rational) time-zone))
222   (let* ((year (if (< year 100)
223                    (pick-obvious-year year)
224                    year))
225          (days (+ (1- date)
226                   (aref *days-before-month* month)
227                   (if (> month 2)
228                       (leap-years-before (1+ year))
229                       (leap-years-before year))
230                   (* (- year 1900) 365)))
231          (hours (+ hour (* days 24))))
232     (if time-zone
233         (+ second (* (+ minute (* (+ hours time-zone) 60)) 60))
234         (let* ((minwest-guess
235                 (nth-value 1
236                            (get-timezone (- (* hours 60 60)
237                                             unix-to-universal-time))))
238                (guess (+ minute (* hours 60) minwest-guess))
239                (minwest
240                 (nth-value 1
241                            (get-timezone (- (* guess 60)
242                                             unix-to-universal-time)))))
243           (+ second (* (+ guess (- minwest minwest-guess)) 60))))))
244 \f
245 ;;;; TIME
246
247 (defmacro time (form)
248   #!+sb-doc
249   "Evaluates the Form and prints timing information on *Trace-Output*."
250   `(%time #'(lambda () ,form)))
251
252 ;;; Try to compile the closure arg to %TIME if it is interpreted.
253 (defun massage-time-function (fun)
254   (cond
255    ((sb!eval:interpreted-function-p fun)
256     (multiple-value-bind (def env-p) (function-lambda-expression fun)
257       (declare (ignore def))
258       (cond
259        (env-p
260         (warn "TIME form in a non-null environment, forced to interpret.~@
261                Compiling entire form will produce more accurate times.")
262         fun)
263        (t
264         (compile nil fun)))))
265    (t fun)))
266
267 ;;; Return all the files that we want time to report.
268 (defun time-get-sys-info ()
269   (multiple-value-bind (user sys faults) (sb!sys:get-system-info)
270     (values user sys faults (get-bytes-consed))))
271
272 ;;; The guts of the TIME macro. Compute overheads, run the (compiled)
273 ;;; function, report the times.
274 (defun %time (fun)
275   (let ((fun (massage-time-function fun))
276         old-run-utime
277         new-run-utime
278         old-run-stime
279         new-run-stime
280         old-real-time
281         new-real-time
282         old-page-faults
283         new-page-faults
284         real-time-overhead
285         run-utime-overhead
286         run-stime-overhead
287         page-faults-overhead
288         old-bytes-consed
289         new-bytes-consed
290         cons-overhead)
291     ;; Calculate the overhead...
292     (multiple-value-setq
293         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
294       (time-get-sys-info))
295     ;; Do it a second time to make sure everything is faulted in.
296     (multiple-value-setq
297         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
298       (time-get-sys-info))
299     (multiple-value-setq
300         (new-run-utime new-run-stime new-page-faults new-bytes-consed)
301       (time-get-sys-info))
302     (setq run-utime-overhead (- new-run-utime old-run-utime))
303     (setq run-stime-overhead (- new-run-stime old-run-stime))
304     (setq page-faults-overhead (- new-page-faults old-page-faults))
305     (setq old-real-time (get-internal-real-time))
306     (setq old-real-time (get-internal-real-time))
307     (setq new-real-time (get-internal-real-time))
308     (setq real-time-overhead (- new-real-time old-real-time))
309     (setq cons-overhead (- new-bytes-consed old-bytes-consed))
310     ;; Now get the initial times.
311     (multiple-value-setq
312         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
313       (time-get-sys-info))
314     (setq old-real-time (get-internal-real-time))
315     (let ((start-gc-run-time *gc-run-time*))
316     (multiple-value-prog1
317         ;; Execute the form and return its values.
318         (funcall fun)
319       (multiple-value-setq
320           (new-run-utime new-run-stime new-page-faults new-bytes-consed)
321         (time-get-sys-info))
322       (setq new-real-time (- (get-internal-real-time) real-time-overhead))
323       (let ((gc-run-time (max (- *gc-run-time* start-gc-run-time) 0)))
324         (format *trace-output*
325                 "~&Evaluation took:~%  ~
326                  ~S second~:P of real time~%  ~
327                  ~S second~:P of user run time~%  ~
328                  ~S second~:P of system run time~%  ~
329 ~@[                 [Run times include ~S second~:P GC run time.]~%  ~]~
330                  ~S page fault~:P and~%  ~
331                  ~S bytes consed.~%"
332                 (max (/ (- new-real-time old-real-time)
333                         (float internal-time-units-per-second))
334                      0.0)
335                 (max (/ (- new-run-utime old-run-utime) 1000000.0) 0.0)
336                 (max (/ (- new-run-stime old-run-stime) 1000000.0) 0.0)
337                 (unless (zerop gc-run-time)
338                   (/ (float gc-run-time)
339                      (float internal-time-units-per-second)))
340                 (max (- new-page-faults old-page-faults) 0)
341                 (max (- new-bytes-consed old-bytes-consed) 0)))))))