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