Debian Codegraph @

contrib/profile/profile.lisp

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