0.9.3.38: further fixes to ENCODE- and DECODE-UNIVERSAL-TIME:
[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 sb!xc:internal-time-units-per-second 1000
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 sb!xc: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. (See
31   INTERNAL-TIME-UNITS-PER-SECOND.) This is useful for finding elapsed time."
32   (multiple-value-bind (ignore seconds useconds) (sb!unix:unix-gettimeofday)
33     (declare (ignore ignore) (type (unsigned-byte 32) seconds useconds))
34     (let ((base *internal-real-time-base-seconds*)
35           (uint (truncate useconds
36                           micro-seconds-per-internal-time-unit)))
37       (declare (type (unsigned-byte 32) uint))
38       (cond (base
39              (truly-the (unsigned-byte 32)
40                         (+ (the (unsigned-byte 32)
41                                 (* (the (unsigned-byte 32) (- seconds base))
42                                    sb!xc:internal-time-units-per-second))
43                            uint)))
44             (t
45              (setq *internal-real-time-base-seconds* seconds)
46              uint)))))
47
48 (defun get-internal-run-time ()
49   #!+sb-doc
50   "Return the run time in the internal time format. (See
51   INTERNAL-TIME-UNITS-PER-SECOND.) This is useful for finding CPU usage."
52   (declare (values (unsigned-byte 32)))
53   (multiple-value-bind (ignore utime-sec utime-usec stime-sec stime-usec)
54       (sb!unix:unix-fast-getrusage sb!unix:rusage_self)
55     (declare (ignore ignore)
56              (type (unsigned-byte 31) utime-sec stime-sec)
57              ;; (Classic CMU CL had these (MOD 1000000) instead, but
58              ;; at least in Linux 2.2.12, the type doesn't seem to be
59              ;; documented anywhere and the observed behavior is to
60              ;; sometimes return 1000000 exactly.)
61              (type (integer 0 1000000) utime-usec stime-usec))
62     (let ((result (+ (the (unsigned-byte 32)
63                           (* (the (unsigned-byte 32) (+ utime-sec stime-sec))
64                              sb!xc:internal-time-units-per-second))
65                      (floor (+ utime-usec
66                                stime-usec
67                                (floor micro-seconds-per-internal-time-unit 2))
68                             micro-seconds-per-internal-time-unit))))
69       result)))
70 \f
71 ;;;; Encode and decode universal times.
72
73 ;;; In August 2003, work was done in this file for more plausible
74 ;;; timezone handling after the unix timezone database runs out in
75 ;;; 2038.  We assume that timezone rules are trending sane rather than
76 ;;; insane, so for all years after the end of time_t we apply the
77 ;;; rules for 2035/2036 instead of the actual date asked for.  Making
78 ;;; the same assumption about the early 1900s would be less
79 ;;; reasonable, however, so please note that we're still broken for
80 ;;; local time between 1900-1-1 and 1901-12-13
81
82 ;;; It should be noted that 64 bit machines don't actually fix this
83 ;;; problem, at least as of 2003, because the Unix zonefiles are
84 ;;; specified in terms of 32 bit fields even on, say, the Alpha.  So,
85 ;;; references to the range of time_t elsewhere in this file should
86 ;;; rightly be read as shorthand for the range of an signed 32 bit
87 ;;; number of seconds since 1970-01-01
88
89 ;;; I'm obliged to Erik Naggum's "Long, Painful History of Time" paper
90 ;;; <http://heim.ifi.uio.no/~enag/lugm-time.html> for the choice of epoch
91 ;;; here.  By starting the year in March, we avoid having to test the month
92 ;;; whenever deciding whether to account for a leap day.  2000 is especially
93 ;;; special, because it's disvisible by 400, hence the start of a 400 year
94 ;;; leap year cycle
95
96 ;;; If a universal-time is after time_t runs out, we find its offset
97 ;;; from 1st March of whichever year it falls in, then add that to
98 ;;; 2035-3-1.  This date has two relevant properties: (1) somewhere
99 ;;; near the end of time_t, and (2) preceding a leap year.  Thus a
100 ;;; date which is e.g. 365.5 days from March 1st in its year will be
101 ;;; treated for timezone lookup as if it were Feb 29th 2036
102
103 ;;; This epoch is used only for fixing the timezones-outside-time_t
104 ;;; problem.  Someday it would be nice to come back to this code and
105 ;;; see if the rest of the file and its references to Spice Lisp
106 ;;; history (Perq time base?) could be cleaned up any on this basis.
107 ;;; -- dan, 2003-08-08
108
109 ;;; In order to accomodate universal times between January 1st 1900
110 ;;; and sometime on December 13th 1901, I'm doing the same calculation
111 ;;; as described above in order to handle dates in that interval, by
112 ;;; normalizing them to March 1st 1903, which shares the same special
113 ;;; properties described above (except for the 400-year property, but
114 ;;; this isn't an issue for the limited range we need to handle).
115
116 ;;; One open issue is whether to pass UNIX a 64-bit time_t value on
117 ;;; 64-bit platforms. I don't know if time_t is always 64-bit on those
118 ;;; platforms, and looking at this file reveals a scary amount of
119 ;;; literal 31 and 32s.
120 ;;; -- bem, 2005-08-09
121
122 ;;; Subtract from the returned Internal-Time to get the universal
123 ;;; time. The offset between our time base and the Perq one is 2145
124 ;;; weeks and five days.
125 (defconstant seconds-in-week (* 60 60 24 7))
126 (defconstant weeks-offset 2145)
127 (defconstant seconds-offset 432000)
128 (defconstant minutes-per-day (* 24 60))
129 (defconstant quarter-days-per-year (1+ (* 365 4)))
130 (defconstant quarter-days-per-century 146097)
131 (defconstant november-17-1858 678882)
132 (defconstant weekday-november-17-1858 2)
133 (defconstant unix-to-universal-time 2208988800)
134
135 (defun get-universal-time ()
136   #!+sb-doc
137   "Return a single integer for the current time of
138    day in universal time format."
139   (multiple-value-bind (res secs) (sb!unix:unix-gettimeofday)
140     (declare (ignore res))
141     (+ secs unix-to-universal-time)))
142
143 (defun get-decoded-time ()
144   #!+sb-doc
145   "Return nine values specifying the current time as follows:
146    second, minute, hour, date, month, year, day of week (0 = Monday), T
147    (daylight savings times) or NIL (standard time), and timezone."
148   (decode-universal-time (get-universal-time)))
149
150 (defconstant +mar-1-2000+ #.(encode-universal-time 0 0 0 1 3 2000 0))
151 (defconstant +mar-1-2035+ #.(encode-universal-time 0 0 0 1 3 2035 0))
152
153 (defconstant +mar-1-1903+ #.(encode-universal-time 0 0 0 1 3 1903 0))
154
155 (defun years-since-mar-2000 (utime)
156   "Returns number of complete years since March 1st 2000, and remainder in seconds"
157   (let* ((days-in-year (* 86400 365))
158          (days-in-4year (+ (* 4 days-in-year) 86400))
159          (days-in-100year (- (* 25 days-in-4year) 86400))
160          (days-in-400year (+ (* 4 days-in-100year) 86400))
161          (offset (- utime +mar-1-2000+))
162          (year 0))
163     (labels ((whole-num (x y inc max)
164                (let ((w (truncate x y)))
165                  (when (and max (> w max)) (setf w max))
166                  (incf year (* w inc))
167                  (* w y))))
168       (decf offset (whole-num offset days-in-400year 400 nil))
169       (decf offset (whole-num offset days-in-100year 100 3))
170       (decf offset (whole-num offset days-in-4year 4 25))
171       (decf offset (whole-num offset days-in-year 1 3))
172       (values year offset))))
173
174 (defun truncate-to-unix-range (utime)
175   (let ((unix-time (- utime unix-to-universal-time)))
176     (cond
177       ((< unix-time (- (ash 1 31)))
178        (multiple-value-bind (year offset) (years-since-mar-2000 utime)
179          (declare (ignore year))
180          (+  +mar-1-1903+  (- unix-to-universal-time)  offset)))
181       ((>= unix-time (ash 1 31))
182        (multiple-value-bind (year offset) (years-since-mar-2000 utime)
183          (declare (ignore year))
184          (+  +mar-1-2035+  (- unix-to-universal-time)  offset)))
185       (t unix-time))))
186   
187 (defun decode-universal-time (universal-time &optional time-zone)
188   #!+sb-doc
189   "Converts a universal-time to decoded time format returning the following
190    nine values: second, minute, hour, date, month, year, day of week (0 =
191    Monday), T (daylight savings time) or NIL (standard time), and timezone.
192    Completely ignores daylight-savings-time when time-zone is supplied."
193   (multiple-value-bind (daylight seconds-west)
194       (if time-zone
195           (values nil (* time-zone 60 60))
196           (multiple-value-bind (ignore seconds-west daylight)
197               (sb!unix::get-timezone (truncate-to-unix-range universal-time))
198             (declare (ignore ignore))
199             (declare (fixnum seconds-west))
200             (values daylight seconds-west)))
201     (declare (fixnum seconds-west))
202     (multiple-value-bind (weeks secs)
203         (truncate (+ (- universal-time seconds-west) seconds-offset)
204                   seconds-in-week)
205       (let ((weeks (+ weeks weeks-offset)))
206         (multiple-value-bind (t1 second)
207             (truncate secs 60)
208           (let ((tday (truncate t1 minutes-per-day)))
209             (multiple-value-bind (hour minute)
210                 (truncate (- t1 (* tday minutes-per-day)) 60)
211               (let* ((t2 (1- (* (+ (* weeks 7) tday november-17-1858) 4)))
212                      (tcent (truncate t2 quarter-days-per-century)))
213                 (setq t2 (mod t2 quarter-days-per-century))
214                 (setq t2 (+ (- t2 (mod t2 4)) 3))
215                 (let* ((year (+ (* tcent 100)
216                                 (truncate t2 quarter-days-per-year)))
217                        (days-since-mar0
218                         (1+ (truncate (mod t2 quarter-days-per-year) 4)))
219                        (day (mod (+ tday weekday-november-17-1858) 7))
220                        (t3 (+ (* days-since-mar0 5) 456)))
221                   (cond ((>= t3 1989)
222                          (setq t3 (- t3 1836))
223                          (setq year (1+ year))))
224                   (multiple-value-bind (month t3)
225                       (truncate t3 153)
226                     (let ((date (1+ (truncate t3 5))))
227                       (values second minute hour date month year day
228                               daylight
229                               (if daylight
230                                   (1+ (/ seconds-west 60 60))
231                                   (/ seconds-west 60 60))))))))))))))
232
233 (defun pick-obvious-year (year)
234   (declare (type (mod 100) year))
235   (let* ((current-year (nth-value 5 (get-decoded-time)))
236          (guess (+ year (* (truncate (- current-year 50) 100) 100))))
237     (declare (type (integer 1900 9999) current-year guess))
238     (if (> (- current-year guess) 50)
239         (+ guess 100)
240         guess)))
241
242 (defun leap-years-before (year)
243   (let ((years (- year 1901)))
244     (+ (- (truncate years 4)
245           (truncate years 100))
246        (truncate (+ years 300) 400))))
247
248 (defvar *days-before-month*
249   #.(let ((reversed-result nil)
250           (sum 0))
251       (push nil reversed-result)
252       (dolist (days-in-month '(31 28 31 30 31 30 31 31 30 31 30 31))
253         (push sum reversed-result)
254         (incf sum days-in-month))
255       (coerce (nreverse reversed-result) 'simple-vector)))
256
257
258 (defun encode-universal-time (second minute hour date month year
259                                      &optional time-zone)
260   #!+sb-doc
261   "The time values specified in decoded format are converted to
262    universal time, which is returned."
263   (declare (type (mod 60) second)
264            (type (mod 60) minute)
265            (type (mod 24) hour)
266            (type (integer 1 31) date)
267            (type (integer 1 12) month)
268            (type (or (integer 0 99) (integer 1899)) year)
269            ;; that type used to say (integer 1900), but that's
270            ;; incorrect when a time-zone is specified: we should be
271            ;; able to encode to produce 0 when a non-zero timezone is
272            ;; specified - bem, 2005-08-09
273            (type (or null rational) time-zone))
274   (let* ((year (if (< year 100)
275                    (pick-obvious-year year)
276                    year))
277          (days (+ (1- date)
278                   (aref *days-before-month* month)
279                   (if (> month 2)
280                       (leap-years-before (1+ year))
281                       (leap-years-before year))
282                   (* (- year 1900) 365)))
283          (hours (+ hour (* days 24)))
284          (encoded-time 0))
285     (if time-zone
286         (setf encoded-time (+ second (* (+ minute (* (+ hours time-zone) 60)) 60)))
287         (let* ((secwest-guess
288                 (sb!unix::unix-get-seconds-west
289                  (truncate-to-unix-range (* hours 60 60))))
290                (guess (+ second (* 60 (+ minute (* hours 60)))
291                          secwest-guess))
292                (secwest
293                 (sb!unix::unix-get-seconds-west
294                  (truncate-to-unix-range guess))))
295           (setf encoded-time (+ guess (- secwest secwest-guess)))))
296     (assert (typep encoded-time '(integer 0)))
297     encoded-time))
298 \f
299 ;;;; TIME
300
301 (defvar *gc-run-time* 0
302   #!+sb-doc
303   "the total CPU time spent doing garbage collection (as reported by
304    GET-INTERNAL-RUN-TIME)")
305 (declaim (type index *gc-run-time*))
306
307 (defmacro time (form)
308   #!+sb-doc
309   "Execute FORM and print timing information on *TRACE-OUTPUT*."
310   `(%time (lambda () ,form)))
311
312 ;;; Return all the data that we want TIME to report.
313 (defun time-get-sys-info ()
314   (multiple-value-bind (user sys faults) (sb!sys:get-system-info)
315     (values user sys faults (get-bytes-consed))))
316
317 ;;; The guts of the TIME macro. Compute overheads, run the (compiled)
318 ;;; function, report the times.
319 (defun %time (fun)
320   (declare (type function fun))
321   (let (old-run-utime
322         new-run-utime
323         old-run-stime
324         new-run-stime
325         old-real-time
326         new-real-time
327         old-page-faults
328         new-page-faults
329         real-time-overhead
330         run-utime-overhead
331         run-stime-overhead
332         page-faults-overhead
333         old-bytes-consed
334         new-bytes-consed
335         cons-overhead)
336     ;; Calculate the overhead...
337     (multiple-value-setq
338         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
339       (time-get-sys-info))
340     ;; Do it a second time to make sure everything is faulted in.
341     (multiple-value-setq
342         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
343       (time-get-sys-info))
344     (multiple-value-setq
345         (new-run-utime new-run-stime new-page-faults new-bytes-consed)
346       (time-get-sys-info))
347     (setq run-utime-overhead (- new-run-utime old-run-utime))
348     (setq run-stime-overhead (- new-run-stime old-run-stime))
349     (setq page-faults-overhead (- new-page-faults old-page-faults))
350     (setq old-real-time (get-internal-real-time))
351     (setq old-real-time (get-internal-real-time))
352     (setq new-real-time (get-internal-real-time))
353     (setq real-time-overhead (- new-real-time old-real-time))
354     (setq cons-overhead (- new-bytes-consed old-bytes-consed))
355     ;; Now get the initial times.
356     (multiple-value-setq
357         (old-run-utime old-run-stime old-page-faults old-bytes-consed)
358       (time-get-sys-info))
359     (setq old-real-time (get-internal-real-time))
360     (let ((start-gc-run-time *gc-run-time*))
361     (multiple-value-prog1
362         ;; Execute the form and return its values.
363         (funcall fun)
364       (multiple-value-setq
365           (new-run-utime new-run-stime new-page-faults new-bytes-consed)
366         (time-get-sys-info))
367       (setq new-real-time (- (get-internal-real-time) real-time-overhead))
368       (let ((gc-run-time (max (- *gc-run-time* start-gc-run-time) 0)))
369         (format *trace-output*
370                 "~&Evaluation took:~%  ~
371                  ~S second~:P of real time~%  ~
372                  ~S second~:P of user run time~%  ~
373                  ~S second~:P of system run time~%  ~
374 ~@[                 [Run times include ~S second~:P GC run time.]~%  ~]~
375                  ~S page fault~:P and~%  ~
376                  ~:D bytes consed.~%"
377                 (max (/ (- new-real-time old-real-time)
378                         (float sb!xc:internal-time-units-per-second))
379                      0.0)
380                 (max (/ (- new-run-utime old-run-utime) 1000000.0) 0.0)
381                 (max (/ (- new-run-stime old-run-stime) 1000000.0) 0.0)
382                 (unless (zerop gc-run-time)
383                   (/ (float gc-run-time)
384                      (float sb!xc:internal-time-units-per-second)))
385                 (max (- new-page-faults old-page-faults) 0)
386                 (max (- new-bytes-consed old-bytes-consed) 0)))))))