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