Tolerate non-simple strings when checking arguments to CERROR.
[sbcl.git] / src / code / time.lisp
blob9db32edc615f20a2b3b03b7fe8e59c1ebd2bb9fa
1 ;;;; low-level time functions
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.
12 (in-package "SB!IMPL")
14 (defun time-reinit ()
15 (reinit-internal-real-time))
17 ;;; Implemented in unix.lisp and win32.lisp.
18 (setf (fdocumentation 'get-internal-real-time 'function)
19 "Return the real time (\"wallclock time\") since startup in the internal
20 time format. (See INTERNAL-TIME-UNITS-PER-SECOND.)")
22 (defun get-internal-run-time ()
23 "Return the run time used by the process in the internal time format. (See
24 INTERNAL-TIME-UNITS-PER-SECOND.) This is useful for finding CPU usage.
25 Includes both \"system\" and \"user\" time."
26 (system-internal-run-time))
28 ;;;; Encode and decode universal times.
30 ;;; In August 2003, work was done in this file for more plausible
31 ;;; timezone handling after the unix timezone database runs out in
32 ;;; 2038. We assume that timezone rules are trending sane rather than
33 ;;; insane, so for all years after the end of time_t we apply the
34 ;;; rules for 2035/2036 instead of the actual date asked for. Making
35 ;;; the same assumption about the early 1900s would be less
36 ;;; reasonable, however, so please note that we're still broken for
37 ;;; local time between 1900-1-1 and 1901-12-13
39 ;;; It should be noted that 64 bit machines don't actually fix this
40 ;;; problem, at least as of 2003, because the Unix zonefiles are
41 ;;; specified in terms of 32 bit fields even on, say, the Alpha. So,
42 ;;; references to the range of time_t elsewhere in this file should
43 ;;; rightly be read as shorthand for the range of an signed 32 bit
44 ;;; number of seconds since 1970-01-01
46 ;;; I'm obliged to Erik Naggum's "Long, Painful History of Time" paper
47 ;;; <http://naggum.no/lugm-time.html> for the choice of epoch here.
48 ;;; By starting the year in March, we avoid having to test the month
49 ;;; whenever deciding whether to account for a leap day. 2000 is
50 ;;; especially special, because it's divisible by 400, hence the start
51 ;;; of a 400 year leap year cycle
53 ;;; If a universal-time is after time_t runs out, we find its offset
54 ;;; from 1st March of whichever year it falls in, then add that to
55 ;;; 2035-3-1. This date has two relevant properties: (1) somewhere
56 ;;; near the end of time_t, and (2) preceding a leap year. Thus a
57 ;;; date which is e.g. 365.5 days from March 1st in its year will be
58 ;;; treated for timezone lookup as if it were Feb 29th 2036
60 ;;; This epoch is used only for fixing the timezones-outside-time_t
61 ;;; problem. Someday it would be nice to come back to this code and
62 ;;; see if the rest of the file and its references to Spice Lisp
63 ;;; history (Perq time base?) could be cleaned up any on this basis.
64 ;;; -- dan, 2003-08-08
66 ;;; In order to accomodate universal times between January 1st 1900
67 ;;; and sometime on December 13th 1901, I'm doing the same calculation
68 ;;; as described above in order to handle dates in that interval, by
69 ;;; normalizing them to March 1st 1903, which shares the same special
70 ;;; properties described above (except for the 400-year property, but
71 ;;; this isn't an issue for the limited range we need to handle).
73 ;;; One open issue is whether to pass UNIX a 64-bit time_t value on
74 ;;; 64-bit platforms. I don't know if time_t is always 64-bit on those
75 ;;; platforms, and looking at this file reveals a scary amount of
76 ;;; literal 31 and 32s.
77 ;;; -- bem, 2005-08-09
79 ;;; Subtract from the returned Internal-Time to get the universal
80 ;;; time. The offset between our time base and the Perq one is 2145
81 ;;; weeks and five days.
82 (defconstant seconds-in-week (* 60 60 24 7))
83 (defconstant weeks-offset 2145)
84 (defconstant seconds-offset 432000)
85 (defconstant minutes-per-day (* 24 60))
86 (defconstant quarter-days-per-year (1+ (* 365 4)))
87 (defconstant quarter-days-per-century 146097)
88 (defconstant november-17-1858 678882)
89 (defconstant weekday-november-17-1858 2)
90 (defconstant unix-to-universal-time 2208988800)
92 (defun get-universal-time ()
93 "Return a single integer for the current time of day in universal time
94 format."
95 (+ (get-time-of-day) unix-to-universal-time))
97 (defun get-decoded-time ()
98 "Return nine values specifying the current time as follows:
99 second, minute, hour, date, month, year, day of week (0 = Monday), T
100 (daylight savings times) or NIL (standard time), and timezone."
101 (decode-universal-time (get-universal-time)))
103 (defconstant +mar-1-2000+ #.(encode-universal-time 0 0 0 1 3 2000 0))
104 (defconstant +mar-1-2035+ #.(encode-universal-time 0 0 0 1 3 2035 0))
106 (defconstant +mar-1-1903+ #.(encode-universal-time 0 0 0 1 3 1903 0))
108 (defun years-since-mar-2000 (utime)
109 "Returns number of complete years since March 1st 2000, and remainder in seconds"
110 (let* ((days-in-year (* 86400 365))
111 (days-in-4year (+ (* 4 days-in-year) 86400))
112 (days-in-100year (- (* 25 days-in-4year) 86400))
113 (days-in-400year (+ (* 4 days-in-100year) 86400))
114 (offset (- utime +mar-1-2000+))
115 (year 0))
116 (labels ((whole-num (x y inc max)
117 (let ((w (truncate x y)))
118 (when (and max (> w max)) (setf w max))
119 (incf year (* w inc))
120 (* w y))))
121 (decf offset (whole-num offset days-in-400year 400 nil))
122 (decf offset (whole-num offset days-in-100year 100 3))
123 (decf offset (whole-num offset days-in-4year 4 25))
124 (decf offset (whole-num offset days-in-year 1 3))
125 (values year offset))))
127 (defun truncate-to-unix-range (utime)
128 (let ((unix-time (- utime unix-to-universal-time)))
129 (cond
130 ((< unix-time (- (ash 1 31)))
131 (multiple-value-bind (year offset) (years-since-mar-2000 utime)
132 (declare (ignore year))
133 (+ +mar-1-1903+ (- unix-to-universal-time) offset)))
134 ((>= unix-time (ash 1 31))
135 (multiple-value-bind (year offset) (years-since-mar-2000 utime)
136 (declare (ignore year))
137 (+ +mar-1-2035+ (- unix-to-universal-time) offset)))
138 (t unix-time))))
140 (defun decode-universal-time (universal-time &optional time-zone)
141 "Converts a universal-time to decoded time format returning the following
142 nine values: second, minute, hour, date, month, year, day of week (0 =
143 Monday), T (daylight savings time) or NIL (standard time), and timezone.
144 Completely ignores daylight-savings-time when time-zone is supplied."
145 (multiple-value-bind (seconds-west daylight)
146 (if time-zone
147 (values (* time-zone 60 60) nil)
148 (sb!unix::get-timezone (truncate-to-unix-range universal-time)))
149 (declare (fixnum seconds-west))
150 (multiple-value-bind (weeks secs)
151 (truncate (+ (- universal-time seconds-west) seconds-offset)
152 seconds-in-week)
153 (let ((weeks (+ weeks weeks-offset)))
154 (multiple-value-bind (t1 second)
155 (truncate secs 60)
156 (let ((tday (truncate t1 minutes-per-day)))
157 (multiple-value-bind (hour minute)
158 (truncate (- t1 (* tday minutes-per-day)) 60)
159 (let* ((t2 (1- (* (+ (* weeks 7) tday november-17-1858) 4)))
160 (tcent (truncate t2 quarter-days-per-century)))
161 (setq t2 (mod t2 quarter-days-per-century))
162 (setq t2 (+ (- t2 (mod t2 4)) 3))
163 (let* ((year (+ (* tcent 100)
164 (truncate t2 quarter-days-per-year)))
165 (days-since-mar0
166 (1+ (truncate (mod t2 quarter-days-per-year) 4)))
167 (day (mod (+ tday weekday-november-17-1858) 7))
168 (t3 (+ (* days-since-mar0 5) 456)))
169 (cond ((>= t3 1989)
170 (setq t3 (- t3 1836))
171 (setq year (1+ year))))
172 (multiple-value-bind (month t3)
173 (truncate t3 153)
174 (let ((date (1+ (truncate t3 5))))
175 (values second minute hour date month year day
176 daylight
177 (if daylight
178 (1+ (/ seconds-west 60 60))
179 (/ seconds-west 60 60))))))))))))))
181 (defun pick-obvious-year (year)
182 (declare (type (mod 100) year))
183 (let* ((current-year (nth-value 5 (get-decoded-time)))
184 (guess (+ year (* (truncate (- current-year 50) 100) 100))))
185 (declare (type (integer 1900 9999) current-year guess))
186 (if (> (- current-year guess) 50)
187 (+ guess 100)
188 guess)))
190 (defun leap-years-before (year)
191 (let ((years (- year 1901)))
192 (+ (- (truncate years 4)
193 (truncate years 100))
194 (truncate (+ years 300) 400))))
196 (defglobal **days-before-month**
197 #.(let ((reversed-result nil)
198 (sum 0))
199 (push nil reversed-result)
200 (dolist (days-in-month '(31 28 31 30 31 30 31 31 30 31 30 31))
201 (push sum reversed-result)
202 (incf sum days-in-month))
203 (coerce (nreverse reversed-result) 'simple-vector)))
205 (declaim (type (simple-vector 13) **days-before-month**))
207 (defun encode-universal-time (second minute hour date month year
208 &optional time-zone)
209 "The time values specified in decoded format are converted to
210 universal time, which is returned."
211 (declare (type (mod 60) second)
212 (type (mod 60) minute)
213 (type (mod 24) hour)
214 (type (integer 1 31) date)
215 (type (integer 1 12) month)
216 (type (or (integer 0 99) (integer 1899)) year)
217 ;; that type used to say (integer 1900), but that's
218 ;; incorrect when a time-zone is specified: we should be
219 ;; able to encode to produce 0 when a non-zero timezone is
220 ;; specified - bem, 2005-08-09
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 (truly-the (mod 335)
227 (svref **days-before-month** month))
228 (if (> month 2)
229 (leap-years-before (1+ year))
230 (leap-years-before year))
231 (* (- year 1900) 365)))
232 (hours (+ hour (* days 24)))
233 (encoded-time 0))
234 (if time-zone
235 (setf encoded-time (+ second (* (+ minute (* (+ hours time-zone) 60)) 60)))
236 (let* ((secwest-guess
237 (sb!unix::get-timezone
238 (truncate-to-unix-range (* hours 60 60))))
239 (guess (+ second (* 60 (+ minute (* hours 60)))
240 secwest-guess))
241 (secwest
242 (sb!unix::get-timezone
243 (truncate-to-unix-range guess))))
244 (setf encoded-time (+ guess (- secwest secwest-guess)))))
245 (assert (typep encoded-time '(integer 0)))
246 encoded-time))
248 ;;;; TIME
250 (defvar *gc-run-time* 0
251 "Total CPU time spent doing garbage collection (as reported by
252 GET-INTERNAL-RUN-TIME.) Initialized to zero on startup. It is safe to bind
253 this to zero in order to measure GC time inside a certain section of code, but
254 doing so may interfere with results reported by eg. TIME.")
255 (declaim (type index *gc-run-time*))
257 (defun print-time (&key real-time-ms user-run-time-us system-run-time-us
258 gc-run-time-ms processor-cycles eval-calls
259 lambdas-converted page-faults bytes-consed
260 aborted)
261 (let ((total-run-time-us (+ user-run-time-us system-run-time-us))
262 ;; Arbitrary truncation of the timing output is worthless,
263 ;; and it's only an artifact of the use of a single format control,
264 ;; not "by design" that it should respect *print-length*.
265 (*print-length* nil))
266 (format *trace-output*
267 "~&Evaluation took:~%~
268 ~@< ~@;~/sb-impl::format-milliseconds/ of real time~%~
269 ~/sb-impl::format-microseconds/ of total run time ~
270 (~@/sb-impl::format-microseconds/ user, ~@/sb-impl::format-microseconds/ system)~%~
271 ~[[ Run times consist of ~/sb-impl::format-milliseconds/ GC time, ~
272 and ~/sb-impl::format-milliseconds/ non-GC time. ]~%~;~2*~]~
273 ~,2F% CPU~%~
274 ~@[~:D form~:P interpreted~%~]~
275 ~@[~:D lambda~:P converted~%~]~
276 ~@[~:D processor cycles~%~]~
277 ~@[~:D page fault~:P~%~]~
278 ~:D bytes consed~%~
279 ~@[~%before it was aborted by a non-local transfer of control.~%~]~:>~%"
280 real-time-ms
281 total-run-time-us
282 user-run-time-us
283 system-run-time-us
284 (if (zerop gc-run-time-ms) 1 0)
285 gc-run-time-ms
286 ;; Round up so we don't mislead by saying 0.0 seconds of non-GC time...
287 (- (ceiling total-run-time-us 1000) gc-run-time-ms)
288 (if (zerop real-time-ms)
289 100.0
290 (float (* 100 (/ (round total-run-time-us 1000) real-time-ms))))
291 eval-calls
292 lambdas-converted
293 processor-cycles
294 page-faults
295 bytes-consed
296 aborted)))
298 (defmacro time (form)
299 "Execute FORM and print timing information on *TRACE-OUTPUT*.
301 On some hardware platforms estimated processor cycle counts are
302 included in this output; this number is slightly inflated, since it
303 includes the pipeline involved in reading the cycle counter --
304 executing \(TIME NIL) a few times will give you an idea of the
305 overhead, and its variance. The cycle counters are also per processor,
306 not per thread: if multiple threads are running on the same processor,
307 the reported counts will include cycles taken up by all threads
308 running on the processor where TIME was executed. Furthermore, if the
309 operating system migrates the thread to another processor between
310 reads of the cycle counter, the results will be completely bogus.
311 Finally, the counter is cycle counter, incremented by the hardware
312 even when the process is halted -- which is to say that cycles pass
313 normally during operations like SLEEP."
314 `(call-with-timing #'print-time (lambda () ,form)))
316 ;;; Return all the data that we want TIME to report.
317 (defun time-get-sys-info ()
318 (multiple-value-bind (user sys faults) (sb!sys:get-system-info)
319 (values user sys faults (get-bytes-consed))))
321 (defun elapsed-cycles (h0 l0 h1 l1)
322 (declare (ignorable h0 l0 h1 l1))
323 #!+cycle-counter
324 (+ (ash (- h1 h0) 32)
325 (- l1 l0))
326 #!-cycle-counter
327 nil)
328 (declaim (inline read-cycle-counter))
329 (defun read-cycle-counter ()
330 #!+cycle-counter
331 (sb!vm::%read-cycle-counter)
332 #!-cycle-counter
333 (values 0 0))
335 ;;; This is so that we don't have to worry about the vagaries of
336 ;;; floating point printing, or about conversions to floats dropping
337 ;;; or introducing decimals, which are liable to imply wrong precision.
338 (defun format-microseconds (stream usec &optional colonp atp)
339 (declare (ignore colonp))
340 (%format-decimal stream usec 6)
341 (unless atp
342 (write-string " seconds" stream)))
344 (defun format-milliseconds (stream usec &optional colonp atp)
345 (declare (ignore colonp))
346 (%format-decimal stream usec 3)
347 (unless atp
348 (write-string " seconds" stream)))
350 (defun %format-decimal (stream number power)
351 (declare (stream stream)
352 (integer number power))
353 (when (minusp number)
354 (write-char #\- stream)
355 (setf number (- number)))
356 (let ((scale (expt 10 power)))
357 (labels ((%fraction (fraction)
358 (if (zerop fraction)
359 (%zeroes)
360 (let ((scaled (* 10 fraction)))
361 (loop while (< scaled scale)
362 do (write-char #\0 stream)
363 (setf scaled (* scaled 10)))))
364 (format stream "~D" fraction))
365 (%zeroes ()
366 (let ((scaled (/ scale 10)))
367 (write-char #\0 stream)
368 (loop while (> scaled 1)
369 do (write-char #\0 stream)
370 (setf scaled (/ scaled 10))))))
371 (cond ((zerop number)
372 (write-string "0." stream)
373 (%zeroes))
374 ((< number scale)
375 (write-string "0." stream)
376 (%fraction number))
377 ((= number scale)
378 (write-string "1." stream)
379 (%zeroes))
380 ((> number scale)
381 (multiple-value-bind (whole fraction) (floor number scale)
382 (format stream "~D." whole)
383 (%fraction fraction))))))
384 nil)
386 ;;; The guts of the TIME macro. Compute overheads, run the (compiled)
387 ;;; function, report the times.
388 (defun call-with-timing (timer function &rest arguments)
389 "Calls FUNCTION with ARGUMENTS, and gathers timing information about it.
390 Then calls TIMER with keyword arguments describing the information collected.
391 Calls TIMER even if FUNCTION performs a non-local transfer of control. Finally
392 returns values returned by FUNCTION.
394 :USER-RUN-TIME-US
395 User run time in microseconds.
397 :SYSTEM-RUN-TIME-US
398 System run time in microseconds.
400 :REAL-TIME-MS
401 Real time in milliseconds.
403 :GC-RUN-TIME-MS
404 GC run time in milliseconds (included in user and system run time.)
406 :PROCESSOR-CYCLES
407 Approximate number of processor cycles used. (Omitted if not supported on
408 the platform -- currently available on x86 and x86-64 only.)
410 :EVAL-CALLS
411 Number of calls to EVAL. (Omitted if zero.)
413 :LAMBDAS-CONVERTED
414 Number of lambdas converted. (Omitted if zero.)
416 :PAGE-FAULTS
417 Number of page faults. (Omitted if zero.)
419 :BYTES-CONSED
420 Approximate number of bytes consed.
422 :ABORTED
423 True if FUNCTION caused a non-local transfer of control. (Omitted if
424 NIL.)
426 EXPERIMENTAL: Interface subject to change."
427 (let (old-run-utime
428 new-run-utime
429 old-run-stime
430 new-run-stime
431 old-real-time
432 new-real-time
433 old-page-faults
434 new-page-faults
435 real-time-overhead
436 run-utime-overhead
437 run-stime-overhead
438 page-faults-overhead
439 old-bytes-consed
440 new-bytes-consed
441 cons-overhead
442 (fun (if (functionp function) function (fdefinition function))))
443 (declare (function fun))
444 ;; Calculate the overhead...
445 (multiple-value-setq
446 (old-run-utime old-run-stime old-page-faults old-bytes-consed)
447 (time-get-sys-info))
448 ;; Do it a second time to make sure everything is faulted in.
449 (multiple-value-setq
450 (old-run-utime old-run-stime old-page-faults old-bytes-consed)
451 (time-get-sys-info))
452 (multiple-value-setq
453 (new-run-utime new-run-stime new-page-faults new-bytes-consed)
454 (time-get-sys-info))
455 (setq run-utime-overhead (- new-run-utime old-run-utime))
456 (setq run-stime-overhead (- new-run-stime old-run-stime))
457 (setq page-faults-overhead (- new-page-faults old-page-faults))
458 (setq old-real-time (get-internal-real-time))
459 (setq old-real-time (get-internal-real-time))
460 (setq new-real-time (get-internal-real-time))
461 (setq real-time-overhead (- new-real-time old-real-time))
462 (setq cons-overhead (- new-bytes-consed old-bytes-consed))
463 ;; Now get the initial times.
464 (multiple-value-setq
465 (old-run-utime old-run-stime old-page-faults old-bytes-consed)
466 (time-get-sys-info))
467 (setq old-real-time (get-internal-real-time))
468 (let ((start-gc-internal-run-time *gc-run-time*)
469 (*eval-calls* 0)
470 (sb!c::*lambda-conversions* 0)
471 (aborted t))
472 (declare (special *eval-calls* sb!c::*lambda-conversions*))
473 (multiple-value-bind (h0 l0) (read-cycle-counter)
474 (unwind-protect
475 (multiple-value-prog1 (apply fun arguments)
476 (setf aborted nil))
477 (multiple-value-bind (h1 l1) (read-cycle-counter)
478 (let ((stop-gc-internal-run-time *gc-run-time*))
479 (multiple-value-setq
480 (new-run-utime new-run-stime new-page-faults new-bytes-consed)
481 (time-get-sys-info))
482 (setq new-real-time (- (get-internal-real-time) real-time-overhead))
483 (let* ((gc-internal-run-time (max (- stop-gc-internal-run-time start-gc-internal-run-time) 0))
484 (real-time (max (- new-real-time old-real-time) 0))
485 (user-run-time (max (- new-run-utime old-run-utime) 0))
486 (system-run-time (max (- new-run-stime old-run-stime) 0))
487 (cycles (elapsed-cycles h0 l0 h1 l1))
488 (page-faults (max (- new-page-faults old-page-faults) 0)))
489 (let (plist)
490 (flet ((note (name value &optional test)
491 (unless (and test (funcall test value))
492 (setf plist (list* name value plist)))))
493 (note :aborted aborted #'not)
494 (note :bytes-consed (max (- new-bytes-consed old-bytes-consed) 0))
495 (note :page-faults page-faults #'zerop)
496 ;; cycle counting isn't supported everywhere.
497 (when cycles
498 (note :processor-cycles cycles #'zerop))
499 (note :lambdas-converted sb!c::*lambda-conversions* #'zerop)
500 (note :eval-calls *eval-calls* #'zerop)
501 (note :gc-run-time-ms gc-internal-run-time)
502 (note :system-run-time-us system-run-time)
503 (note :user-run-time-us user-run-time)
504 (note :real-time-ms real-time))
505 (apply timer plist))))))))))