Initial revision
[sbcl.git] / src / code / profile.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3 ;;;;
4 ;;;; This software is derived from the CMU CL system, which was
5 ;;;; written at Carnegie Mellon University and released into the
6 ;;;; public domain. The software is in the public domain and is
7 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
8 ;;;; files for more information.
9
10 (in-package "SB-PROFILE")
11 \f
12 ;;;; reading internal run time with high resolution and low overhead
13
14 ;;; FIXME: It might make sense to replace this with something
15 ;;; with finer resolution, e.g. milliseconds or microseconds.
16
17 (defconstant +ticks-per-second+ internal-time-units-per-second)
18
19 (declaim (inline get-internal-ticks))
20 (defun get-internal-ticks () (get-internal-run-time))
21 \f
22 ;;;; PCOUNTER
23
24 ;;; a PCOUNTER is used to represent an integer quantity which can grow
25 ;;; bigger than a fixnum, but typically does so, if at all, in many
26 ;;; small steps, where we don't want to cons on every step. (Total
27 ;;; system consing, time spent in a profiled function, and bytes
28 ;;; consed in a profiled function are all examples of such
29 ;;; quantities.)
30 (defstruct (pcounter (:copier nil))
31   (integer 0 :type integer)
32   (fixnum 0 :type fixnum))
33
34 (declaim (ftype (function (pcounter integer) pcounter) incf-pcounter))
35 (declaim (inline incf-pcounter))
36 (defun incf-pcounter (pcounter delta)
37   (let ((sum (+ (pcounter-fixnum pcounter) delta)))
38     (cond ((typep sum 'fixnum)
39            (setf (pcounter-fixnum pcounter) sum))
40           (t
41            (incf (pcounter-integer pcounter) sum)
42            (setf (pcounter-fixnum pcounter) 0))))
43   pcounter)
44
45 (declaim (ftype (function (pcounter) integer) pcounter->integer))
46 (declaim (inline pcounter->integer))
47 (defun pcounter->integer (pcounter)
48   (+ (pcounter-integer pcounter)
49      (pcounter-fixnum pcounter)))
50 \f
51 ;;;; operations on (OR PCOUNTER FIXNUM)
52 ;;;;
53 ;;;; When we don't want to cons a PCOUNTER unless we're forced to, we
54 ;;;; start with a FIXNUM counter and only create a PCOUNTER if the
55 ;;;; FIXNUM overflows.
56
57 (declaim (ftype (function ((or pcounter fixnum) integer) (or pcounter fixnum)) %incf-pcounter-or-fixnum))
58 (declaim (inline %incf-pcounter-or-fixnum))
59 (defun %incf-pcounter-or-fixnum (x delta)
60   (etypecase x
61     (fixnum
62      (let ((sum (+ x delta)))
63        (if (typep sum 'fixnum)
64            sum
65            (make-pcounter :integer sum))))
66     (pcounter
67      (incf-pcounter x delta))))
68   
69 (define-modify-macro incf-pcounter-or-fixnum (delta) %incf-pcounter-or-fixnum)
70
71 ;;; Trade off space for execution time by handling the common fast
72 ;;; (TYPEP DELTA 'FIXNUM) case inline and only calling generic
73 ;;; arithmetic as a last resort.
74 (defmacro fastbig-incf-pcounter-or-fixnum (x delta)
75   (once-only ((delta delta))
76     `(etypecase ,delta
77        (fixnum (incf-pcounter-or-fixnum ,x ,delta))
78        (integer (incf-pcounter-or-fixnum ,x ,delta)))))
79
80 (declaim (ftype (function ((or pcounter fixnum)) integer) pcounter-or-fixnum->integer))
81 (declaim (maybe-inline pcounter-or-fixnum->integer))
82 (defun pcounter-or-fixnum->integer (x)
83   (etypecase x
84     (fixnum x)
85     (pcounter (pcounter->integer x))))
86 \f
87 ;;;; implementation-dependent interfaces
88
89 #|
90 ;;; To avoid unnecessary consing in the "encapsulation" code, we want
91 ;;; find out the number of required arguments, and use &REST to
92 ;;; capture only non-required arguments. This function returns (VALUES
93 ;;; MIN-ARGS OPTIONALS-P), where MIN-ARGS is the number of required
94 ;;; arguments and OPTIONALS-P is true iff there are any non-required
95 ;;; arguments (such as &OPTIONAL, &REST, or &KEY).
96 (declaim (ftype (function ((or symbol cons)) (values fixnum t)) fun-signature))
97 (defun fun-signature (name)
98   (let ((type (info :function :type name)))
99     (cond ((not (function-type-p type))
100            (values 0 t))
101           (t
102            (values (length (function-type-required type))
103                    (or (function-type-optional type)
104                        (function-type-keyp type)
105                        (function-type-rest type)))))))
106 |#
107 \f
108 ;;;; global data structures
109
110 ;;; We associate a PROFILE-INFO structure with each profiled function
111 ;;; name. This holds the functions that we call to manipulate the
112 ;;; closure which implements the encapsulation.
113 (defvar *profiled-function-name->info* (make-hash-table))
114 (defstruct profile-info
115   (name              (required-argument) :read-only t)
116   (encapsulated-fun  (required-argument) :type function :read-only t)
117   (encapsulation-fun (required-argument) :type function :read-only t)
118   (read-stats-fun    (required-argument) :type function :read-only t)
119   (clear-stats-fun   (required-argument) :type function :read-only t))
120
121 ;;; These variables are used to subtract out the time and consing for
122 ;;; recursive and other dynamically nested profiled calls. The total
123 ;;; resource consumed for each nested call is added into the
124 ;;; appropriate variable. When the outer function returns, these
125 ;;; amounts are subtracted from the total.
126 (defvar *enclosed-ticks* 0)
127 (defvar *enclosed-consing* 0)
128 (declaim (type (or pcounter fixnum) *enclosed-ticks* *enclosed-consing*))
129
130 ;;; This variable is also used to subtract out time for nested
131 ;;; profiled calls. The time inside the profile wrapper call --
132 ;;; between its two calls to GET-INTERNAL-TICKS -- is accounted
133 ;;; for by the *ENCLOSED-TIME* variable. However, there's also extra
134 ;;; overhead involved, before we get to the first call to
135 ;;; GET-INTERNAL-TICKS, and after we get to the second call. By
136 ;;; keeping track of the count of enclosed profiled calls, we can try
137 ;;; to compensate for that.
138 (defvar *enclosed-profiles* 0)
139 (declaim (type (or pcounter fixnum) *enclosed-profiles*))
140
141 ;;; the components of profiling overhead
142 (defstruct overhead
143   ;; the number of ticks a bare function call takes. This is
144   ;; factored into the other overheads, but not used for itself.
145   (call (required-argument) :type single-float :read-only t)
146   ;; the number of ticks that will be charged to a profiled
147   ;; function due to the profiling code
148   (internal (required-argument) :type single-float :read-only t)
149   ;; the number of ticks of overhead for profiling that a single
150   ;; profiled call adds to the total runtime for the program
151   (total (required-argument) :type single-float :read-only t))
152 (defvar *overhead*)
153 (declaim (type overhead *overhead*))
154 \f
155 ;;;; profile encapsulations
156
157 ;;; Trade off space for time by handling the usual all-FIXNUM cases
158 ;;; inline.
159 (defmacro fastbig- (x y)
160   (once-only ((x x) (y y))
161     `(if (and (typep ,x 'fixnum)
162               (typep ,y 'fixnum))
163          (- ,x ,y)
164          (- ,x ,y))))
165 (defmacro fastbig-1+ (x)
166   (once-only ((x x))
167     `(if (typep ,x 'index)
168          (1+ ,x)
169          (1+ ,x))))
170
171 ;;; Return a collection of closures over the same lexical context,
172 ;;;   (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
173 ;;;
174 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
175 ;;; which updates statistics whenver it's called.
176 ;;;
177 ;;; READ-STATS-FUN returns the statistics:
178 ;;;   (VALUES COUNT TIME CONSING PROFILE).
179 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
180 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
181 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
182 ;;; number of calls to the profiled function, stored for the purposes
183 ;;; of trying to estimate that part of profiling overhead which occurs
184 ;;; outside the interval between the profile wrapper function's timer
185 ;;; calls.
186 ;;;
187 ;;; CLEAR-STATS-FUN clears the statistics.
188 ;;;
189 ;;; (The reason for implementing this as coupled closures, with the
190 ;;; counts built into the lexical environment, is that we hopes this
191 ;;; will minimize profiling overhead.)
192 (defun profile-encapsulation-lambdas (encapsulated-fun)
193   (declare (type function encapsulated-fun))
194   (declare (optimize speed safety))
195   (let* ((count 0)
196          (ticks 0)
197          (consing 0)
198          (profiles 0))
199     (declare (type (or pcounter fixnum) count ticks consing profiles))
200     (values
201      ;; ENCAPSULATION-FUN
202      (lambda (sb-c:&more arg-context arg-count)
203        #+nil (declare (optimize (speed 3) (safety 0))) ; FIXME: remove #+NIL?
204        (fastbig-incf-pcounter-or-fixnum count 1)
205        (let ((dticks 0)
206              (dconsing 0)
207              (inner-enclosed-profiles 0))
208          (declare (type unsigned-byte dticks dconsing))
209          (declare (type unsigned-byte inner-enclosed-profiles))
210          (multiple-value-prog1
211              (let ((start-ticks (get-internal-ticks))
212                    ;; KLUDGE: We add (THE UNSIGNED-BYTE ..) wrappers
213                    ;; around GET-BYTES-CONSED because as of
214                    ;; sbcl-0.6.4, at the time that the FTYPE of
215                    ;; GET-BYTES-CONSED is DECLAIMed, the
216                    ;; cross-compiler's type system isn't mature enough
217                    ;; to do anything about it. -- WHN 20000503
218                    (start-consing (the unsigned-byte (get-bytes-consed)))
219                    (*enclosed-ticks* 0)
220                    (*enclosed-consing* 0)
221                    (*enclosed-profiles* 0))
222                (declare (inline pcounter-or-fixnum->integer))
223                (multiple-value-prog1
224                    (multiple-value-call encapsulated-fun
225                                         (sb-c:%more-arg-values arg-context
226                                                                0
227                                                                arg-count))
228                  (setf dticks (fastbig- (get-internal-ticks) start-ticks)
229                        dconsing (fastbig- (the unsigned-byte
230                                                (get-bytes-consed))
231                                           start-consing))
232                  (setf inner-enclosed-profiles
233                        (pcounter-or-fixnum->integer *enclosed-profiles*))
234                  (fastbig-incf-pcounter-or-fixnum ticks (fastbig-
235                                                          dticks
236                                                          *enclosed-ticks*))
237                  (fastbig-incf-pcounter-or-fixnum consing
238                                                   (fastbig-
239                                                    dconsing
240                                                    *enclosed-consing*))
241                  (fastbig-incf-pcounter-or-fixnum profiles
242                                                   inner-enclosed-profiles)))
243            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
244            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
245            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
246                                             (fastbig-1+
247                                              inner-enclosed-profiles)))))
248      ;; READ-STATS-FUN
249      (lambda ()
250        (values (pcounter-or-fixnum->integer count)
251                (pcounter-or-fixnum->integer ticks)
252                (pcounter-or-fixnum->integer consing)
253                (pcounter-or-fixnum->integer profiles)))
254      ;; CLEAR-STATS-FUN
255      (lambda ()
256        (setf count 0
257              ticks 0
258              consing 0
259              profiles 0)))))
260 \f
261 ;;; interfaces
262
263 ;;; A symbol names a function, a string names all the functions named
264 ;;; by symbols in the named package.
265 (defun mapc-on-named-functions (function names)
266   (dolist (name names)
267     (etypecase name
268       (symbol (funcall function name))
269       (string (let ((package (find-undeleted-package-or-lose name)))
270                 (do-symbols (symbol package)
271                   (when (eq (symbol-package symbol) package)
272                     (when (fboundp symbol)
273                       (funcall function symbol))
274                     (let ((setf-name `(setf ,symbol)))
275                       (when (fboundp setf-name)
276                         (funcall function setf-name)))))))))
277   (values))
278
279 ;;; Profile the named function, which should exist and not be profiled
280 ;;; already.
281 (defun profile-1-unprofiled-function (name)
282   (let ((encapsulated-fun (fdefinition name)))
283     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
284         (profile-encapsulation-lambdas encapsulated-fun)
285       (setf (fdefinition name)
286             encapsulation-fun)
287       (setf (gethash name *profiled-function-name->info*)
288             (make-profile-info :name name
289                                :encapsulated-fun encapsulated-fun
290                                :encapsulation-fun encapsulation-fun
291                                :read-stats-fun read-stats-fun
292                                :clear-stats-fun clear-stats-fun))
293       (values))))
294
295 ;;; Profile the named function. If already profiled, unprofile first.
296 (defun profile-1-function (name)
297   (cond ((fboundp name)
298          (when (gethash name *profiled-function-name->info*)
299            (warn "~S is already profiled, so unprofiling it first." name)
300            (unprofile-1-function name))
301          (profile-1-unprofiled-function name))
302         (t
303          (warn "ignoring undefined function ~S" name)))
304   (values))
305
306 ;;; Unprofile the named function, if it is profiled.
307 (defun unprofile-1-function (name)
308   (let ((pinfo (gethash name *profiled-function-name->info*)))
309     (cond (pinfo
310            (remhash name *profiled-function-name->info*)
311            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
312                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
313                (warn "preserving current definition of redefined function ~S"
314                      name)))
315           (t
316            (warn "~S is not a profiled function."))))
317   (values))
318
319 (defmacro profile (&rest names)
320   #+sb-doc
321   "PROFILE Name*
322
323    If no names are supplied, return the list of profiled functions.
324
325    If names are supplied, wrap profiling code around the named functions.
326    As in TRACE, the names are not evaluated. A symbol names a function.
327    A string names all the functions named by symbols in the named
328    package. If a function is already profiled, then unprofile and
329    reprofile (useful to notice function redefinition.)  If a name is
330    undefined, then we give a warning and ignore it. See also
331    UNPROFILE, REPORT and RESET."
332   (if (null names)
333       `(loop for k being each hash-key in *profiled-function-name->info*
334              collecting k)
335       `(mapc-on-named-functions #'profile-1-function ',names)))
336
337 (defmacro unprofile (&rest names)
338   #+sb-doc
339   "Unwrap any profiling code around the named functions, or if no names
340   are given, unprofile all profiled functions. A symbol names
341   a function. A string names all the functions named by symbols in the
342   named package. NAMES defaults to the list of names of all currently 
343   profiled functions."
344   (if names
345       `(mapc-on-named-functions #'unprofile-1-function ',names)
346       `(unprofile-all)))
347
348 (defun unprofile-all ()
349   (dohash (name profile-info *profiled-function-name->info*)
350     (declare (ignore profile-info))
351     (unprofile-1-function name)))
352
353 (defun reset ()
354   "Reset the counters for all profiled functions."
355   (dohash (name profile-info *profiled-function-name->info*)
356     (declare (ignore name))
357     (funcall (profile-info-clear-stats-fun profile-info))))
358 \f
359 ;;;; reporting results
360
361 (defstruct time-info
362   name
363   calls
364   seconds
365   consing)
366
367 ;;; Return our best guess for the run time in a function, subtracting
368 ;;; out factors for profiling overhead. We subtract out the internal
369 ;;; overhead for each call to this function, since the internal
370 ;;; overhead is the part of the profiling overhead for a function that
371 ;;; is charged to that function.
372 ;;;
373 ;;; We also subtract out a factor for each call to a profiled function
374 ;;; within this profiled function. This factor is the total profiling
375 ;;; overhead *minus the internal overhead*. We don't subtract out the
376 ;;; internal overhead, since it was already subtracted when the nested
377 ;;; profiled functions subtracted their running time from the time for
378 ;;; the enclosing function.
379 (defun compensate-time (calls ticks profile)
380   (let ((raw-compensated
381          (- (/ (float ticks) (float +ticks-per-second+))
382             (* (overhead-internal *overhead*) (float calls))
383             (* (- (overhead-total *overhead*)
384                   (overhead-internal *overhead*))
385                (float profile)))))
386     (max raw-compensated 0.0)))
387
388 (defun report ()
389   "Report results from profiling. The results are
390 approximately adjusted for profiling overhead, but when RAW is true
391 the unadjusted results are reported. The compensation may be somewhat
392 inaccurate when bignums are involved in runtime calculation, as in
393 a very-long-running Lisp process."
394   (declare (optimize (speed 0)))
395   (unless (boundp '*overhead*)
396     (setf *overhead*
397           (compute-overhead)))
398   (let ((time-info-list ())
399         (no-call-name-list ()))
400     (dohash (name pinfo *profiled-function-name->info*)
401       (unless (eq (fdefinition name)
402                   (profile-info-encapsulation-fun pinfo))
403         (warn "Function ~S has been redefined, so times may be inaccurate.~@
404                PROFILE it again to record calls to the new definition."
405               name))
406       (multiple-value-bind (calls ticks consing profile)
407           (funcall (profile-info-read-stats-fun pinfo))
408         (if (zerop calls)
409             (push name no-call-name-list)
410             (push (make-time-info :name name
411                                   :calls calls
412                                   :seconds (compensate-time calls
413                                                             ticks
414                                                             profile)
415                                   :consing consing)
416                   time-info-list))))
417
418     (setf time-info-list
419           (sort time-info-list
420                 #'>=
421                 :key #'time-info-seconds))
422
423     (format *trace-output*
424             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
425                ------------------------------------------------------~%")
426
427     (let ((total-time 0.0)
428           (total-consed 0)
429           (total-calls 0))
430       (dolist (time-info time-info-list)
431         (incf total-time (time-info-seconds time-info))
432         (incf total-calls (time-info-calls time-info))
433         (incf total-consed (time-info-consing time-info))
434         (format *trace-output*
435                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
436                 (time-info-seconds time-info)
437                 (time-info-consing time-info)
438                 (time-info-calls time-info)
439                 (/ (time-info-seconds time-info)
440                    (float (time-info-calls time-info)))
441                 (time-info-name time-info)))
442       (format *trace-output*
443               "------------------------------------------------------~@
444               ~10,3F | ~9:D | ~7:D |        | Total~%"
445               total-time total-consed total-calls)
446       (format *trace-output*
447               "~%estimated total profiling overhead: ~4,2F seconds~%"
448               (* (overhead-total *overhead*) (float total-calls)))
449       (format *trace-output*
450               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
451               (overhead-call *overhead*)
452               (overhead-total *overhead*)
453               (overhead-internal *overhead*)))
454
455     (when no-call-name-list
456       (format *trace-output*
457               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
458               (sort no-call-name-list #'string<
459                     :key (lambda (name)
460                            (symbol-name (function-name-block-name name))))))
461
462     (values)))
463 \f
464 ;;;; overhead estimation
465
466 ;;; We average the timing overhead over this many iterations.
467 (defconstant +timer-overhead-iterations+ 50000)
468
469 ;;; a dummy function that we profile to find profiling overhead
470 (declaim (notinline compute-overhead-aux))
471 (defun compute-overhead-aux (x)
472   (declare (ignore x)))
473
474 ;;; Return a newly computed OVERHEAD object.
475 (defun compute-overhead ()
476   (flet ((frob ()
477            (let ((start (get-internal-ticks))
478                  (fun (symbol-function 'compute-overhead-aux)))
479              (dotimes (i +timer-overhead-iterations+)
480                (funcall fun fun))
481              (/ (float (- (get-internal-ticks) start))
482                 (float +ticks-per-second+)
483                 (float +timer-overhead-iterations+)))))
484     (let (;; Measure unprofiled calls to estimate call overhead.
485           (call-overhead (frob))
486           total-overhead
487           internal-overhead)
488       ;; Measure profiled calls to estimate profiling overhead.
489       (unwind-protect
490           (progn
491             (profile compute-overhead-aux)
492             (setf total-overhead
493                   (- (frob) call-overhead)))
494         (let* ((pinfo (gethash 'compute-overhead-aux
495                                *profiled-function-name->info*))
496                (read-stats-fun (profile-info-read-stats-fun pinfo))
497                (time (nth-value 1 (funcall read-stats-fun))))
498           (setf internal-overhead
499                 (/ (float time)
500                    (float +ticks-per-second+)
501                    (float +timer-overhead-iterations+))))
502         (unprofile compute-overhead-aux))
503       (make-overhead :call call-overhead
504                      :total total-overhead
505                      :internal internal-overhead))))
506
507 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
508 ;;; then load old *OVERHEAD* value from the .core file into a
509 ;;; different machine running at a different speed. We avoid this by
510 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
511 (pushnew (lambda ()
512            (makunbound '*overhead*))
513          *before-save-initializations*)