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