4f4f9ab57a5d02e13766223f39e3826e19e4f8d3
[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 (function-type-p type))
37            (values 0 t))
38           (t
39            (values (length (function-type-required type))
40                    (or (function-type-optional type)
41                        (function-type-keyp type)
42                        (function-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-function-name->info* (make-hash-table))
51 (defstruct (profile-info (:copier nil))
52   (name              (required-argument) :read-only t)
53   (encapsulated-fun  (required-argument) :type function :read-only t)
54   (encapsulation-fun (required-argument) :type function :read-only t)
55   (read-stats-fun    (required-argument) :type function :read-only t)
56   (clear-stats-fun   (required-argument) :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 (required-argument) :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 (required-argument) :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 (required-argument) :type single-float :read-only t))
95 (defvar *overhead*)
96 (declaim (type overhead *overhead*))
97 \f
98 ;;;; profile encapsulations
99
100 ;;; Trade off space for time by handling the usual all-FIXNUM cases
101 ;;; inline.
102 (defmacro fastbig- (x y)
103   (once-only ((x x) (y y))
104     `(if (and (typep ,x 'fixnum)
105               (typep ,y 'fixnum))
106          (- ,x ,y)
107          (- ,x ,y))))
108 (defmacro fastbig-1+ (x)
109   (once-only ((x x))
110     `(if (typep ,x 'index)
111          (1+ ,x)
112          (1+ ,x))))
113
114 ;;; Return a collection of closures over the same lexical context,
115 ;;;   (VALUES ENCAPSULATION-FUN READ-STATS-FUN CLEAR-STATS-FUN).
116 ;;;
117 ;;; ENCAPSULATION-FUN is a plug-in replacement for ENCAPSULATED-FUN,
118 ;;; which updates statistics whenver it's called.
119 ;;;
120 ;;; READ-STATS-FUN returns the statistics:
121 ;;;   (VALUES COUNT TIME CONSING PROFILE).
122 ;;; COUNT is the count of calls to ENCAPSULATION-FUN. TICKS is
123 ;;; the total number of ticks spent in ENCAPSULATED-FUN.
124 ;;; CONSING is the total consing of ENCAPSULATION-FUN. PROFILE is the
125 ;;; number of calls to the profiled function, stored for the purposes
126 ;;; of trying to estimate that part of profiling overhead which occurs
127 ;;; outside the interval between the profile wrapper function's timer
128 ;;; calls.
129 ;;;
130 ;;; CLEAR-STATS-FUN clears the statistics.
131 ;;;
132 ;;; (The reason for implementing this as coupled closures, with the
133 ;;; counts built into the lexical environment, is that we hope this
134 ;;; will minimize profiling overhead.)
135 (defun profile-encapsulation-lambdas (encapsulated-fun)
136   (declare (type function encapsulated-fun))
137   (let* ((count 0)
138          (ticks 0)
139          (consing 0)
140          (profiles 0))
141     (declare (type (or pcounter fixnum) count ticks consing profiles))
142     (values
143      ;; ENCAPSULATION-FUN
144      (lambda (sb-c:&more arg-context arg-count)
145        (declare (optimize speed safety))
146        ;; Make sure that we're not recursing infinitely.
147        (when (boundp '*computing-profiling-data-for*)
148          (unprofile-all) ; to avoid further recursion
149          (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.)~:@>"
150                 *computing-profiling-data-for*
151                 encapsulated-fun
152                 encapsulated-fun))
153        ;; FIXME: Probably when this is stable, we should optimize (SAFETY 0).
154        (fastbig-incf-pcounter-or-fixnum count 1)
155        (let ((dticks 0)
156              (dconsing 0)
157              (inner-enclosed-profiles 0))
158          ;;(declare (type unsigned-byte dticks dconsing))
159          ;;(declare (type unsigned-byte inner-enclosed-profiles))
160          (aver (typep dticks 'unsigned-byte))
161          (aver (typep dconsing 'unsigned-byte))
162          (aver (typep inner-enclosed-profiles 'unsigned-byte))
163          (multiple-value-prog1
164              (let ((start-ticks (get-internal-ticks))
165                    (start-consing (get-bytes-consed))
166                    (*enclosed-ticks* 0)
167                    (*enclosed-consing* 0)
168                    (*enclosed-profiles* 0))
169                (declare (inline pcounter-or-fixnum->integer))
170                (multiple-value-prog1
171                    (multiple-value-call encapsulated-fun
172                                         (sb-c:%more-arg-values arg-context
173                                                                0
174                                                                arg-count))
175                  (let ((*computing-profiling-data-for* encapsulated-fun))
176                    (setf dticks (fastbig- (get-internal-ticks) start-ticks)
177                          dconsing (fastbig- (get-bytes-consed) start-consing))
178                    (setf inner-enclosed-profiles
179                          (pcounter-or-fixnum->integer *enclosed-profiles*))
180                    (aver (not (minusp dconsing))) ; REMOVEME
181                    (aver (not (minusp inner-enclosed-profiles))) ; REMOVEME
182                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
183                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
184                    (let ((net-dconsing (fastbig- dconsing *enclosed-consing*)))
185                      (when (minusp net-dconsing) ; REMOVEME
186                        (unprofile-all)
187                        (error "huh? DCONSING=~S, *ENCLOSED-CONSING*=~S"
188                               dticks *enclosed-ticks*))
189                      (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
190                    (fastbig-incf-pcounter-or-fixnum profiles
191                                                     inner-enclosed-profiles))))
192            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
193            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
194            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
195                                             (fastbig-1+
196                                              inner-enclosed-profiles)))))
197      ;; READ-STATS-FUN
198      (lambda ()
199        (values (pcounter-or-fixnum->integer count)
200                (pcounter-or-fixnum->integer ticks)
201                (pcounter-or-fixnum->integer consing)
202                (pcounter-or-fixnum->integer profiles)))
203      ;; CLEAR-STATS-FUN
204      (lambda ()
205        (setf count 0
206              ticks 0
207              consing 0
208              profiles 0)))))
209 \f
210 ;;;; interfaces
211
212 ;;; A symbol or (SETF FOO) list names a function, a string names all
213 ;;; the functions named by symbols in the named package.
214 (defun mapc-on-named-functions (function names)
215   (dolist (name names)
216     (etypecase name
217       (symbol (funcall function name))
218       (list
219        ;; We call this just for the side effect of checking that
220        ;; NAME is a legal function name:
221        (function-name-block-name name)
222        ;; Then we map onto it.
223        (funcall function name))
224       (string (let ((package (find-undeleted-package-or-lose name)))
225                 (do-symbols (symbol package)
226                   (when (eq (symbol-package symbol) package)
227                     (when (fboundp symbol)
228                       (funcall function symbol))
229                     (let ((setf-name `(setf ,symbol)))
230                       (when (fboundp setf-name)
231                         (funcall function setf-name)))))))))
232   (values))
233
234 ;;; Profile the named function, which should exist and not be profiled
235 ;;; already.
236 (defun profile-1-unprofiled-function (name)
237   (declare #.*optimize-byte-compilation*)
238   (let ((encapsulated-fun (fdefinition name)))
239     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
240         (profile-encapsulation-lambdas encapsulated-fun)
241       (setf (fdefinition name)
242             encapsulation-fun)
243       (setf (gethash name *profiled-function-name->info*)
244             (make-profile-info :name name
245                                :encapsulated-fun encapsulated-fun
246                                :encapsulation-fun encapsulation-fun
247                                :read-stats-fun read-stats-fun
248                                :clear-stats-fun clear-stats-fun))
249       (values))))
250
251 ;;; Profile the named function. If already profiled, unprofile first.
252 (defun profile-1-function (name)
253   (declare #.*optimize-byte-compilation*)
254   (cond ((fboundp name)
255          (when (gethash name *profiled-function-name->info*)
256            (warn "~S is already profiled, so unprofiling it first." name)
257            (unprofile-1-function name))
258          (profile-1-unprofiled-function name))
259         (t
260          (warn "ignoring undefined function ~S" name)))
261   (values))
262
263 ;;; Unprofile the named function, if it is profiled.
264 (defun unprofile-1-function (name)
265   (declare #.*optimize-byte-compilation*)
266   (let ((pinfo (gethash name *profiled-function-name->info*)))
267     (cond (pinfo
268            (remhash name *profiled-function-name->info*)
269            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
270                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
271                (warn "preserving current definition of redefined function ~S"
272                      name)))
273           (t
274            (warn "~S is not a profiled function." name))))
275   (values))
276
277 (defmacro profile (&rest names)
278   #+sb-doc
279   "PROFILE Name*
280
281    If no names are supplied, return the list of profiled functions.
282
283    If names are supplied, wrap profiling code around the named functions.
284    As in TRACE, the names are not evaluated. A symbol names a function.
285    A string names all the functions named by symbols in the named
286    package. If a function is already profiled, then unprofile and
287    reprofile (useful to notice function redefinition.)  If a name is
288    undefined, then we give a warning and ignore it. See also
289    UNPROFILE, REPORT and RESET."
290   (declare #.*optimize-byte-compilation*)
291   (if (null names)
292       `(loop for k being each hash-key in *profiled-function-name->info*
293              collecting k)
294       `(mapc-on-named-functions #'profile-1-function ',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   (declare #.*optimize-byte-compilation*)
304   (if names
305       `(mapc-on-named-functions #'unprofile-1-function ',names)
306       `(unprofile-all)))
307
308 (defun unprofile-all ()
309   (declare #.*optimize-byte-compilation*)
310   (dohash (name profile-info *profiled-function-name->info*)
311     (declare (ignore profile-info))
312     (unprofile-1-function name)))
313
314 (defun reset ()
315   "Reset the counters for all profiled functions."
316   (dohash (name profile-info *profiled-function-name->info*)
317     (declare (ignore name))
318     (funcall (profile-info-clear-stats-fun profile-info))))
319 \f
320 ;;;; reporting results
321
322 (defstruct (time-info (:copier nil))
323   name
324   calls
325   seconds
326   consing)
327
328 ;;; Return our best guess for the run time in a function, subtracting
329 ;;; out factors for profiling overhead. We subtract out the internal
330 ;;; overhead for each call to this function, since the internal
331 ;;; overhead is the part of the profiling overhead for a function that
332 ;;; is charged to that function.
333 ;;;
334 ;;; We also subtract out a factor for each call to a profiled function
335 ;;; within this profiled function. This factor is the total profiling
336 ;;; overhead *minus the internal overhead*. We don't subtract out the
337 ;;; internal overhead, since it was already subtracted when the nested
338 ;;; profiled functions subtracted their running time from the time for
339 ;;; the enclosing function.
340 (defun compensate-time (calls ticks profile)
341   (let ((raw-compensated
342          (- (/ (float ticks) (float +ticks-per-second+))
343             (* (overhead-internal *overhead*) (float calls))
344             (* (- (overhead-total *overhead*)
345                   (overhead-internal *overhead*))
346                (float profile)))))
347     (max raw-compensated 0.0)))
348
349 (defun report ()
350   "Report results from profiling. The results are
351 approximately adjusted for profiling overhead, but when RAW is true
352 the unadjusted results are reported. The compensation may be somewhat
353 inaccurate when bignums are involved in runtime calculation, as in
354 a very-long-running Lisp process."
355   (declare #.*optimize-external-despite-byte-compilation*)
356   (unless (boundp '*overhead*)
357     (setf *overhead*
358           (compute-overhead)))
359   (let ((time-info-list ())
360         (no-call-name-list ()))
361     (dohash (name pinfo *profiled-function-name->info*)
362       (unless (eq (fdefinition name)
363                   (profile-info-encapsulation-fun pinfo))
364         (warn "Function ~S has been redefined, so times may be inaccurate.~@
365                PROFILE it again to record calls to the new definition."
366               name))
367       (multiple-value-bind (calls ticks consing profile)
368           (funcall (profile-info-read-stats-fun pinfo))
369         (if (zerop calls)
370             (push name no-call-name-list)
371             (push (make-time-info :name name
372                                   :calls calls
373                                   :seconds (compensate-time calls
374                                                             ticks
375                                                             profile)
376                                   :consing consing)
377                   time-info-list))))
378
379     (setf time-info-list
380           (sort time-info-list
381                 #'>=
382                 :key #'time-info-seconds))
383
384     (format *trace-output*
385             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
386                ------------------------------------------------------~%")
387
388     (let ((total-time 0.0)
389           (total-consed 0)
390           (total-calls 0))
391       (dolist (time-info time-info-list)
392         (incf total-time (time-info-seconds time-info))
393         (incf total-calls (time-info-calls time-info))
394         (incf total-consed (time-info-consing time-info))
395         (format *trace-output*
396                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
397                 (time-info-seconds time-info)
398                 (time-info-consing time-info)
399                 (time-info-calls time-info)
400                 (/ (time-info-seconds time-info)
401                    (float (time-info-calls time-info)))
402                 (time-info-name time-info)))
403       (format *trace-output*
404               "------------------------------------------------------~@
405               ~10,3F | ~9:D | ~7:D |        | Total~%"
406               total-time total-consed total-calls)
407       (format *trace-output*
408               "~%estimated total profiling overhead: ~4,2F seconds~%"
409               (* (overhead-total *overhead*) (float total-calls)))
410       (format *trace-output*
411               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
412               (overhead-call *overhead*)
413               (overhead-total *overhead*)
414               (overhead-internal *overhead*)))
415
416     (when no-call-name-list
417       (format *trace-output*
418               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
419               (sort no-call-name-list #'string<
420                     :key (lambda (name)
421                            (symbol-name (function-name-block-name name))))))
422
423     (values)))
424 \f
425 ;;;; overhead estimation
426
427 ;;; We average the timing overhead over this many iterations.
428 (defconstant +timer-overhead-iterations+
429   50 ; REMOVEME
430   ;;50000
431   )
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   (flet ((frob ()
441            (let ((start (get-internal-ticks))
442                  (fun (symbol-function 'compute-overhead-aux)))
443              (dotimes (i +timer-overhead-iterations+)
444                (funcall fun fun))
445              (/ (float (- (get-internal-ticks) start))
446                 (float +ticks-per-second+)
447                 (float +timer-overhead-iterations+)))))
448     (let (;; Measure unprofiled calls to estimate call overhead.
449           (call-overhead (frob))
450           total-overhead
451           internal-overhead)
452       ;; Measure profiled calls to estimate profiling overhead.
453       (unwind-protect
454           (progn
455             (profile compute-overhead-aux)
456             (setf total-overhead
457                   (- (frob) call-overhead)))
458         (let* ((pinfo (gethash 'compute-overhead-aux
459                                *profiled-function-name->info*))
460                (read-stats-fun (profile-info-read-stats-fun pinfo))
461                (time (nth-value 1 (funcall read-stats-fun))))
462           (setf internal-overhead
463                 (/ (float time)
464                    (float +ticks-per-second+)
465                    (float +timer-overhead-iterations+))))
466         (unprofile compute-overhead-aux))
467       (make-overhead :call call-overhead
468                      :total total-overhead
469                      :internal internal-overhead))))
470
471 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
472 ;;; then load old *OVERHEAD* value from the .core file into a
473 ;;; different machine running at a different speed. We avoid this by
474 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
475 (pushnew (lambda ()
476            (makunbound '*overhead*))
477          *before-save-initializations*)