bf9086527c73b4931bd1db96f63091691d447693
[sbcl.git] / 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                    (let ((net-dticks (fastbig- dticks *enclosed-ticks*)))
181                      (fastbig-incf-pcounter-or-fixnum ticks net-dticks))
182                    (let ((net-dconsing (fastbig- dconsing *enclosed-consing*)))
183                      (fastbig-incf-pcounter-or-fixnum consing net-dconsing))
184                    (fastbig-incf-pcounter-or-fixnum profiles
185                                                     inner-enclosed-profiles))))
186            (fastbig-incf-pcounter-or-fixnum *enclosed-ticks* dticks)
187            (fastbig-incf-pcounter-or-fixnum *enclosed-consing* dconsing)
188            (fastbig-incf-pcounter-or-fixnum *enclosed-profiles*
189                                             (fastbig-1+
190                                              inner-enclosed-profiles)))))
191      ;; READ-STATS-FUN
192      (lambda ()
193        (values (pcounter-or-fixnum->integer count)
194                (pcounter-or-fixnum->integer ticks)
195                (pcounter-or-fixnum->integer consing)
196                (pcounter-or-fixnum->integer profiles)))
197      ;; CLEAR-STATS-FUN
198      (lambda ()
199        (setf count 0
200              ticks 0
201              consing 0
202              profiles 0)))))
203 \f
204 ;;;; interfaces
205
206 ;;; A symbol or (SETF FOO) list names a function, a string names all
207 ;;; the functions named by symbols in the named package.
208 (defun mapc-on-named-functions (function names)
209   (dolist (name names)
210     (etypecase name
211       (symbol (funcall function name))
212       (list
213        ;; We call this just for the side effect of checking that
214        ;; NAME is a legal function name:
215        (function-name-block-name name)
216        ;; Then we map onto it.
217        (funcall function name))
218       (string (let ((package (find-undeleted-package-or-lose name)))
219                 (do-symbols (symbol package)
220                   (when (eq (symbol-package symbol) package)
221                     (when (fboundp symbol)
222                       (funcall function symbol))
223                     (let ((setf-name `(setf ,symbol)))
224                       (when (fboundp setf-name)
225                         (funcall function setf-name)))))))))
226   (values))
227
228 ;;; Profile the named function, which should exist and not be profiled
229 ;;; already.
230 (defun profile-1-unprofiled-function (name)
231   (declare #.*optimize-byte-compilation*)
232   (let ((encapsulated-fun (fdefinition name)))
233     (multiple-value-bind (encapsulation-fun read-stats-fun clear-stats-fun)
234         (profile-encapsulation-lambdas encapsulated-fun)
235       (setf (fdefinition name)
236             encapsulation-fun)
237       (setf (gethash name *profiled-function-name->info*)
238             (make-profile-info :name name
239                                :encapsulated-fun encapsulated-fun
240                                :encapsulation-fun encapsulation-fun
241                                :read-stats-fun read-stats-fun
242                                :clear-stats-fun clear-stats-fun))
243       (values))))
244
245 ;;; Profile the named function. If already profiled, unprofile first.
246 (defun profile-1-function (name)
247   (declare #.*optimize-byte-compilation*)
248   (cond ((fboundp name)
249          (when (gethash name *profiled-function-name->info*)
250            (warn "~S is already profiled, so unprofiling it first." name)
251            (unprofile-1-function name))
252          (profile-1-unprofiled-function name))
253         (t
254          (warn "ignoring undefined function ~S" name)))
255   (values))
256
257 ;;; Unprofile the named function, if it is profiled.
258 (defun unprofile-1-function (name)
259   (declare #.*optimize-byte-compilation*)
260   (let ((pinfo (gethash name *profiled-function-name->info*)))
261     (cond (pinfo
262            (remhash name *profiled-function-name->info*)
263            (if (eq (fdefinition name) (profile-info-encapsulation-fun pinfo))
264                (setf (fdefinition name) (profile-info-encapsulated-fun pinfo))
265                (warn "preserving current definition of redefined function ~S"
266                      name)))
267           (t
268            (warn "~S is not a profiled function." name))))
269   (values))
270
271 (defmacro profile (&rest names)
272   #+sb-doc
273   "PROFILE Name*
274
275    If no names are supplied, return the list of profiled functions.
276
277    If names are supplied, wrap profiling code around the named functions.
278    As in TRACE, the names are not evaluated. A symbol names a function.
279    A string names all the functions named by symbols in the named
280    package. If a function is already profiled, then unprofile and
281    reprofile (useful to notice function redefinition.)  If a name is
282    undefined, then we give a warning and ignore it. See also
283    UNPROFILE, REPORT and RESET."
284   (declare #.*optimize-byte-compilation*)
285   (if (null names)
286       `(loop for k being each hash-key in *profiled-function-name->info*
287              collecting k)
288       `(mapc-on-named-functions #'profile-1-function ',names)))
289
290 (defmacro unprofile (&rest names)
291   #+sb-doc
292   "Unwrap any profiling code around the named functions, or if no names
293   are given, unprofile all profiled functions. A symbol names
294   a function. A string names all the functions named by symbols in the
295   named package. NAMES defaults to the list of names of all currently 
296   profiled functions."
297   (declare #.*optimize-byte-compilation*)
298   (if names
299       `(mapc-on-named-functions #'unprofile-1-function ',names)
300       `(unprofile-all)))
301
302 (defun unprofile-all ()
303   (declare #.*optimize-byte-compilation*)
304   (dohash (name profile-info *profiled-function-name->info*)
305     (declare (ignore profile-info))
306     (unprofile-1-function name)))
307
308 (defun reset ()
309   "Reset the counters for all profiled functions."
310   (dohash (name profile-info *profiled-function-name->info*)
311     (declare (ignore name))
312     (funcall (profile-info-clear-stats-fun profile-info))))
313 \f
314 ;;;; reporting results
315
316 (defstruct (time-info (:copier nil))
317   name
318   calls
319   seconds
320   consing)
321
322 ;;; Return our best guess for the run time in a function, subtracting
323 ;;; out factors for profiling overhead. We subtract out the internal
324 ;;; overhead for each call to this function, since the internal
325 ;;; overhead is the part of the profiling overhead for a function that
326 ;;; is charged to that function.
327 ;;;
328 ;;; We also subtract out a factor for each call to a profiled function
329 ;;; within this profiled function. This factor is the total profiling
330 ;;; overhead *minus the internal overhead*. We don't subtract out the
331 ;;; internal overhead, since it was already subtracted when the nested
332 ;;; profiled functions subtracted their running time from the time for
333 ;;; the enclosing function.
334 (defun compensate-time (calls ticks profile)
335   (let ((raw-compensated
336          (- (/ (float ticks) (float +ticks-per-second+))
337             (* (overhead-internal *overhead*) (float calls))
338             (* (- (overhead-total *overhead*)
339                   (overhead-internal *overhead*))
340                (float profile)))))
341     (max raw-compensated 0.0)))
342
343 (defun report ()
344   "Report results from profiling. The results are approximately adjusted
345 for profiling overhead. The compensation may be rather inaccurate when
346 bignums are involved in runtime calculation, as in a very-long-running
347 Lisp process."
348   (declare #.*optimize-external-despite-byte-compilation*)
349   (unless (boundp '*overhead*)
350     (setf *overhead*
351           (compute-overhead)))
352   (let ((time-info-list ())
353         (no-call-name-list ()))
354     (dohash (name pinfo *profiled-function-name->info*)
355       (unless (eq (fdefinition name)
356                   (profile-info-encapsulation-fun pinfo))
357         (warn "Function ~S has been redefined, so times may be inaccurate.~@
358                PROFILE it again to record calls to the new definition."
359               name))
360       (multiple-value-bind (calls ticks consing profile)
361           (funcall (profile-info-read-stats-fun pinfo))
362         (if (zerop calls)
363             (push name no-call-name-list)
364             (push (make-time-info :name name
365                                   :calls calls
366                                   :seconds (compensate-time calls
367                                                             ticks
368                                                             profile)
369                                   :consing consing)
370                   time-info-list))))
371
372     (setf time-info-list
373           (sort time-info-list
374                 #'>=
375                 :key #'time-info-seconds))
376
377     (format *trace-output*
378             "~&  seconds  |  consed   |  calls  |  sec/call  |  name~@
379                ------------------------------------------------------~%")
380
381     (let ((total-time 0.0)
382           (total-consed 0)
383           (total-calls 0))
384       (dolist (time-info time-info-list)
385         (incf total-time (time-info-seconds time-info))
386         (incf total-calls (time-info-calls time-info))
387         (incf total-consed (time-info-consing time-info))
388         (format *trace-output*
389                 "~10,3F | ~9:D | ~7:D | ~10,6F | ~S~%"
390                 (time-info-seconds time-info)
391                 (time-info-consing time-info)
392                 (time-info-calls time-info)
393                 (/ (time-info-seconds time-info)
394                    (float (time-info-calls time-info)))
395                 (time-info-name time-info)))
396       (format *trace-output*
397               "------------------------------------------------------~@
398               ~10,3F | ~9:D | ~7:D |        | Total~%"
399               total-time total-consed total-calls)
400       (format *trace-output*
401               "~%estimated total profiling overhead: ~4,2F seconds~%"
402               (* (overhead-total *overhead*) (float total-calls)))
403       (format *trace-output*
404               "~&overhead estimation parameters:~%  ~Ss/call, ~Ss total profiling, ~Ss internal profiling~%"
405               (overhead-call *overhead*)
406               (overhead-total *overhead*)
407               (overhead-internal *overhead*)))
408
409     (when no-call-name-list
410       (format *trace-output*
411               "~%These functions were not called:~%~{~<~%~:; ~S~>~}~%"
412               (sort no-call-name-list #'string<
413                     :key (lambda (name)
414                            (symbol-name (function-name-block-name name))))))
415
416     (values)))
417 \f
418 ;;;; overhead estimation
419
420 ;;; We average the timing overhead over this many iterations.
421 (defconstant +timer-overhead-iterations+
422   50000)
423
424 ;;; a dummy function that we profile to find profiling overhead
425 (declaim (notinline compute-overhead-aux))
426 (defun compute-overhead-aux (x)
427   (declare (ignore x)))
428
429 ;;; Return a newly computed OVERHEAD object.
430 (defun compute-overhead ()
431   (flet ((frob ()
432            (let ((start (get-internal-ticks))
433                  (fun (symbol-function 'compute-overhead-aux)))
434              (dotimes (i +timer-overhead-iterations+)
435                (funcall fun fun))
436              (/ (float (- (get-internal-ticks) start))
437                 (float +ticks-per-second+)
438                 (float +timer-overhead-iterations+)))))
439     (let (;; Measure unprofiled calls to estimate call overhead.
440           (call-overhead (frob))
441           total-overhead
442           internal-overhead)
443       ;; Measure profiled calls to estimate profiling overhead.
444       (unwind-protect
445           (progn
446             (profile compute-overhead-aux)
447             (setf total-overhead
448                   (- (frob) call-overhead)))
449         (let* ((pinfo (gethash 'compute-overhead-aux
450                                *profiled-function-name->info*))
451                (read-stats-fun (profile-info-read-stats-fun pinfo))
452                (time (nth-value 1 (funcall read-stats-fun))))
453           (setf internal-overhead
454                 (/ (float time)
455                    (float +ticks-per-second+)
456                    (float +timer-overhead-iterations+))))
457         (unprofile compute-overhead-aux))
458       (make-overhead :call call-overhead
459                      :total total-overhead
460                      :internal internal-overhead))))
461
462 ;;; It would be bad to compute *OVERHEAD*, save it into a .core file,
463 ;;; then load old *OVERHEAD* value from the .core file into a
464 ;;; different machine running at a different speed. We avoid this by
465 ;;; erasing *CALL-OVERHEAD* whenever we save a .core file.
466 (pushnew (lambda ()
467            (makunbound '*overhead*))
468          *before-save-initializations*)