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