statprof.scm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. ;;;; (statprof) -- a statistical profiler for Guile
  2. ;;;; -*-scheme-*-
  3. ;;;;
  4. ;;;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
  5. ;;;; Copyright (C) 2004, 2009 Andy Wingo <wingo at pobox dot com>
  6. ;;;; Copyright (C) 2001 Rob Browning <rlb at defaultvalue dot org>
  7. ;;;;
  8. ;;;; This library is free software; you can redistribute it and/or
  9. ;;;; modify it under the terms of the GNU Lesser General Public
  10. ;;;; License as published by the Free Software Foundation; either
  11. ;;;; version 3 of the License, or (at your option) any later version.
  12. ;;;;
  13. ;;;; This library is distributed in the hope that it will be useful,
  14. ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. ;;;; Lesser General Public License for more details.
  17. ;;;;
  18. ;;;; You should have received a copy of the GNU Lesser General Public
  19. ;;;; License along with this library; if not, write to the Free Software
  20. ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. ;;;;
  22. ;;; Commentary:
  23. ;;
  24. ;;@code{(statprof)} is intended to be a fairly simple
  25. ;;statistical profiler for guile. It is in the early stages yet, so
  26. ;;consider its output still suspect, and please report any bugs to
  27. ;;@email{guile-devel at gnu.org}, or to me directly at @email{rlb at
  28. ;;defaultvalue.org}.
  29. ;;
  30. ;;A simple use of statprof would look like this:
  31. ;;
  32. ;;@example
  33. ;; (statprof-reset 0 50000 #t)
  34. ;; (statprof-start)
  35. ;; (do-something)
  36. ;; (statprof-stop)
  37. ;; (statprof-display)
  38. ;;@end example
  39. ;;
  40. ;;This would reset statprof, clearing all accumulated statistics, then
  41. ;;start profiling, run some code, stop profiling, and finally display a
  42. ;;gprof flat-style table of statistics which will look something like
  43. ;;this:
  44. ;;
  45. ;;@example
  46. ;; % cumulative self self total
  47. ;; time seconds seconds calls ms/call ms/call name
  48. ;; 35.29 0.23 0.23 2002 0.11 0.11 -
  49. ;; 23.53 0.15 0.15 2001 0.08 0.08 positive?
  50. ;; 23.53 0.15 0.15 2000 0.08 0.08 +
  51. ;; 11.76 0.23 0.08 2000 0.04 0.11 do-nothing
  52. ;; 5.88 0.64 0.04 2001 0.02 0.32 loop
  53. ;; 0.00 0.15 0.00 1 0.00 150.59 do-something
  54. ;; ...
  55. ;;@end example
  56. ;;
  57. ;;All of the numerical data with the exception of the calls column is
  58. ;;statistically approximate. In the following column descriptions, and
  59. ;;in all of statprof, "time" refers to execution time (both user and
  60. ;;system), not wall clock time.
  61. ;;
  62. ;;@table @asis
  63. ;;@item % time
  64. ;;The percent of the time spent inside the procedure itself
  65. ;;(not counting children).
  66. ;;@item cumulative seconds
  67. ;;The total number of seconds spent in the procedure, including
  68. ;;children.
  69. ;;@item self seconds
  70. ;;The total number of seconds spent in the procedure itself (not counting
  71. ;;children).
  72. ;;@item calls
  73. ;;The total number of times the procedure was called.
  74. ;;@item self ms/call
  75. ;;The average time taken by the procedure itself on each call, in ms.
  76. ;;@item total ms/call
  77. ;;The average time taken by each call to the procedure, including time
  78. ;;spent in child functions.
  79. ;;@item name
  80. ;;The name of the procedure.
  81. ;;@end table
  82. ;;
  83. ;;The profiler uses @code{eq?} and the procedure object itself to
  84. ;;identify the procedures, so it won't confuse different procedures with
  85. ;;the same name. They will show up as two different rows in the output.
  86. ;;
  87. ;;Right now the profiler is quite simplistic. I cannot provide
  88. ;;call-graphs or other higher level information. What you see in the
  89. ;;table is pretty much all there is. Patches are welcome :-)
  90. ;;
  91. ;;@section Implementation notes
  92. ;;
  93. ;;The profiler works by setting the unix profiling signal
  94. ;;@code{ITIMER_PROF} to go off after the interval you define in the call
  95. ;;to @code{statprof-reset}. When the signal fires, a sampling routine is
  96. ;;run which looks at the current procedure that's executing, and then
  97. ;;crawls up the stack, and for each procedure encountered, increments
  98. ;;that procedure's sample count. Note that if a procedure is encountered
  99. ;;multiple times on a given stack, it is only counted once. After the
  100. ;;sampling is complete, the profiler resets profiling timer to fire
  101. ;;again after the appropriate interval.
  102. ;;
  103. ;;Meanwhile, the profiler keeps track, via @code{get-internal-run-time},
  104. ;;how much CPU time (system and user -- which is also what
  105. ;;@code{ITIMER_PROF} tracks), has elapsed while code has been executing
  106. ;;within a statprof-start/stop block.
  107. ;;
  108. ;;The profiler also tries to avoid counting or timing its own code as
  109. ;;much as possible.
  110. ;;
  111. ;;; Code:
  112. ;; When you add new features, please also add tests to ./tests/ if you
  113. ;; have time, and then add the new files to ./run-tests. Also, if
  114. ;; anyone's bored, there are a lot of existing API bits that don't
  115. ;; have tests yet.
  116. ;; TODO
  117. ;;
  118. ;; Check about profiling C functions -- does profiling primitives work?
  119. ;; Also look into stealing code from qprof so we can sample the C stack
  120. ;; Call graphs?
  121. (define-module (statprof)
  122. #:use-module (srfi srfi-1)
  123. #:autoload (ice-9 format) (format)
  124. #:use-module (system vm vm)
  125. #:use-module (system vm frame)
  126. #:use-module (system vm program)
  127. #:export (statprof-active?
  128. statprof-start
  129. statprof-stop
  130. statprof-reset
  131. statprof-accumulated-time
  132. statprof-sample-count
  133. statprof-fold-call-data
  134. statprof-proc-call-data
  135. statprof-call-data-name
  136. statprof-call-data-calls
  137. statprof-call-data-cum-samples
  138. statprof-call-data-self-samples
  139. statprof-call-data->stats
  140. statprof-stats-proc-name
  141. statprof-stats-%-time-in-proc
  142. statprof-stats-cum-secs-in-proc
  143. statprof-stats-self-secs-in-proc
  144. statprof-stats-calls
  145. statprof-stats-self-secs-per-call
  146. statprof-stats-cum-secs-per-call
  147. statprof-display
  148. statprof-display-anomolies
  149. statprof-fetch-stacks
  150. statprof-fetch-call-tree
  151. statprof
  152. with-statprof
  153. gcprof))
  154. ;; This profiler tracks two numbers for every function called while
  155. ;; it's active. It tracks the total number of calls, and the number
  156. ;; of times the function was active when the sampler fired.
  157. ;;
  158. ;; Globally the profiler tracks the total time elapsed and the number
  159. ;; of times the sampler was fired.
  160. ;;
  161. ;; Right now, this profiler is not per-thread and is not thread safe.
  162. (define accumulated-time #f) ; total so far.
  163. (define last-start-time #f) ; start-time when timer is active.
  164. (define sample-count #f) ; total count of sampler calls.
  165. (define sampling-frequency #f) ; in (seconds . microseconds)
  166. (define remaining-prof-time #f) ; time remaining when prof suspended.
  167. (define profile-level 0) ; for user start/stop nesting.
  168. (define %count-calls? #t) ; whether to catch apply-frame.
  169. (define gc-time-taken 0) ; gc time between statprof-start and
  170. ; statprof-stop.
  171. (define record-full-stacks? #f) ; if #t, stash away the stacks
  172. ; for later analysis.
  173. (define stacks '())
  174. ;; procedure-data will be a hash where the key is the function object
  175. ;; itself and the value is the data. The data will be a vector like
  176. ;; this: #(name call-count cum-sample-count self-sample-count)
  177. (define procedure-data #f)
  178. ;; If you change the call-data data structure, you need to also change
  179. ;; sample-uncount-frame.
  180. (define (make-call-data proc call-count cum-sample-count self-sample-count)
  181. (vector proc call-count cum-sample-count self-sample-count))
  182. (define (call-data-proc cd) (vector-ref cd 0))
  183. (define (call-data-name cd) (procedure-name (call-data-proc cd)))
  184. (define (call-data-printable cd)
  185. (or (call-data-name cd)
  186. (with-output-to-string (lambda () (write (call-data-proc cd))))))
  187. (define (call-data-call-count cd) (vector-ref cd 1))
  188. (define (call-data-cum-sample-count cd) (vector-ref cd 2))
  189. (define (call-data-self-sample-count cd) (vector-ref cd 3))
  190. (define (inc-call-data-call-count! cd)
  191. (vector-set! cd 1 (1+ (vector-ref cd 1))))
  192. (define (inc-call-data-cum-sample-count! cd)
  193. (vector-set! cd 2 (1+ (vector-ref cd 2))))
  194. (define (inc-call-data-self-sample-count! cd)
  195. (vector-set! cd 3 (1+ (vector-ref cd 3))))
  196. (define-macro (accumulate-time stop-time)
  197. `(set! accumulated-time
  198. (+ accumulated-time 0.0 (- ,stop-time last-start-time))))
  199. (define (get-call-data proc)
  200. (let ((k (if (or (not (program? proc))
  201. (zero? (program-num-free-variables proc)))
  202. proc
  203. (program-objcode proc))))
  204. (or (hashq-ref procedure-data k)
  205. (let ((call-data (make-call-data proc 0 0 0)))
  206. (hashq-set! procedure-data k call-data)
  207. call-data))))
  208. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  209. ;; SIGPROF handler
  210. (define (sample-stack-procs stack)
  211. (let ((stacklen (stack-length stack))
  212. (hit-count-call? #f))
  213. (if record-full-stacks?
  214. (set! stacks (cons stack stacks)))
  215. (set! sample-count (+ sample-count 1))
  216. ;; Now accumulate stats for the whole stack.
  217. (let loop ((frame (stack-ref stack 0))
  218. (procs-seen (make-hash-table 13))
  219. (self #f))
  220. (cond
  221. ((not frame)
  222. (hash-fold
  223. (lambda (proc val accum)
  224. (inc-call-data-cum-sample-count!
  225. (get-call-data proc)))
  226. #f
  227. procs-seen)
  228. (and=> (and=> self get-call-data)
  229. inc-call-data-self-sample-count!))
  230. ((frame-procedure frame)
  231. => (lambda (proc)
  232. (cond
  233. ((eq? proc count-call)
  234. ;; We're not supposed to be sampling count-call and
  235. ;; its sub-functions, so loop again with a clean
  236. ;; slate.
  237. (set! hit-count-call? #t)
  238. (loop (frame-previous frame) (make-hash-table 13) #f))
  239. (else
  240. (hashq-set! procs-seen proc #t)
  241. (loop (frame-previous frame)
  242. procs-seen
  243. (or self proc))))))
  244. (else
  245. (loop (frame-previous frame) procs-seen self))))
  246. hit-count-call?))
  247. (define inside-profiler? #f)
  248. (define (profile-signal-handler sig)
  249. (set! inside-profiler? #t)
  250. ;; FIXME: with-statprof should be able to set an outer frame for the
  251. ;; stack cut
  252. (if (positive? profile-level)
  253. (let* ((stop-time (get-internal-run-time))
  254. ;; cut down to the signal handler. note that this will only
  255. ;; work if statprof.scm is compiled; otherwise we get
  256. ;; `eval' on the stack instead, because if it's not
  257. ;; compiled, profile-signal-handler is a thunk that
  258. ;; tail-calls eval. perhaps we should always compile the
  259. ;; signal handler instead...
  260. (stack (or (make-stack #t profile-signal-handler)
  261. (pk 'what! (make-stack #t))))
  262. (inside-apply-trap? (sample-stack-procs stack)))
  263. (if (not inside-apply-trap?)
  264. (begin
  265. ;; disabling here is just a little more efficient, but
  266. ;; not necessary given inside-profiler?. We can't just
  267. ;; disable unconditionally at the top of this function
  268. ;; and eliminate inside-profiler? because it seems to
  269. ;; confuse guile wrt re-enabling the trap when
  270. ;; count-call finishes.
  271. (if %count-calls?
  272. (set-vm-trace-level! (the-vm)
  273. (1- (vm-trace-level (the-vm)))))
  274. (accumulate-time stop-time)))
  275. (setitimer ITIMER_PROF
  276. 0 0
  277. (car sampling-frequency)
  278. (cdr sampling-frequency))
  279. (if (not inside-apply-trap?)
  280. (begin
  281. (set! last-start-time (get-internal-run-time))
  282. (if %count-calls?
  283. (set-vm-trace-level! (the-vm)
  284. (1+ (vm-trace-level (the-vm)))))))))
  285. (set! inside-profiler? #f))
  286. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  287. ;; Count total calls.
  288. (define (count-call frame)
  289. (if (not inside-profiler?)
  290. (begin
  291. (accumulate-time (get-internal-run-time))
  292. (and=> (frame-procedure frame)
  293. (lambda (proc)
  294. (inc-call-data-call-count!
  295. (get-call-data proc))))
  296. (set! last-start-time (get-internal-run-time)))))
  297. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  298. (define (statprof-active?)
  299. "Returns @code{#t} if @code{statprof-start} has been called more times
  300. than @code{statprof-stop}, @code{#f} otherwise."
  301. (positive? profile-level))
  302. ;; Do not call this from statprof internal functions -- user only.
  303. (define (statprof-start)
  304. "Start the profiler.@code{}"
  305. ;; After some head-scratching, I don't *think* I need to mask/unmask
  306. ;; signals here, but if I'm wrong, please let me know.
  307. (set! profile-level (+ profile-level 1))
  308. (if (= profile-level 1)
  309. (let* ((rpt remaining-prof-time)
  310. (use-rpt? (and rpt
  311. (or (positive? (car rpt))
  312. (positive? (cdr rpt))))))
  313. (set! remaining-prof-time #f)
  314. (set! last-start-time (get-internal-run-time))
  315. (set! gc-time-taken
  316. (cdr (assq 'gc-time-taken (gc-stats))))
  317. (if use-rpt?
  318. (setitimer ITIMER_PROF 0 0 (car rpt) (cdr rpt))
  319. (setitimer ITIMER_PROF
  320. 0 0
  321. (car sampling-frequency)
  322. (cdr sampling-frequency)))
  323. (if %count-calls?
  324. (add-hook! (vm-apply-hook (the-vm)) count-call))
  325. (set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
  326. #t)))
  327. ;; Do not call this from statprof internal functions -- user only.
  328. (define (statprof-stop)
  329. "Stop the profiler.@code{}"
  330. ;; After some head-scratching, I don't *think* I need to mask/unmask
  331. ;; signals here, but if I'm wrong, please let me know.
  332. (set! profile-level (- profile-level 1))
  333. (if (zero? profile-level)
  334. (begin
  335. (set! gc-time-taken
  336. (- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
  337. (set-vm-trace-level! (the-vm) (1- (vm-trace-level (the-vm))))
  338. (if %count-calls?
  339. (remove-hook! (vm-apply-hook (the-vm)) count-call))
  340. ;; I believe that we need to do this before getting the time
  341. ;; (unless we want to make things even more complicated).
  342. (set! remaining-prof-time (setitimer ITIMER_PROF 0 0 0 0))
  343. (accumulate-time (get-internal-run-time))
  344. (set! last-start-time #f))))
  345. (define* (statprof-reset sample-seconds sample-microseconds count-calls?
  346. #:optional full-stacks?)
  347. "Reset the statprof sampler interval to @var{sample-seconds} and
  348. @var{sample-microseconds}. If @var{count-calls?} is true, arrange to
  349. instrument procedure calls as well as collecting statistical profiling
  350. data. If @var{full-stacks?} is true, collect all sampled stacks into a
  351. list for later analysis.
  352. Enables traps and debugging as necessary."
  353. (if (positive? profile-level)
  354. (error "Can't reset profiler while profiler is running."))
  355. (set! %count-calls? count-calls?)
  356. (set! accumulated-time 0)
  357. (set! last-start-time #f)
  358. (set! sample-count 0)
  359. (set! sampling-frequency (cons sample-seconds sample-microseconds))
  360. (set! remaining-prof-time #f)
  361. (set! procedure-data (make-hash-table 131))
  362. (set! record-full-stacks? full-stacks?)
  363. (set! stacks '())
  364. (sigaction SIGPROF profile-signal-handler)
  365. #t)
  366. (define (statprof-fold-call-data proc init)
  367. "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
  368. called while statprof is active. @var{proc} should take two arguments,
  369. @code{(@var{call-data} @var{prior-result})}.
  370. Note that a given proc-name may appear multiple times, but if it does,
  371. it represents different functions with the same name."
  372. (if (positive? profile-level)
  373. (error "Can't call statprof-fold-called while profiler is running."))
  374. (hash-fold
  375. (lambda (key value prior-result)
  376. (proc value prior-result))
  377. init
  378. procedure-data))
  379. (define (statprof-proc-call-data proc)
  380. "Returns the call-data associated with @var{proc}, or @code{#f} if
  381. none is available."
  382. (if (positive? profile-level)
  383. (error "Can't call statprof-fold-called while profiler is running."))
  384. (hashq-ref procedure-data proc))
  385. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  386. ;; Stats
  387. (define (statprof-call-data->stats call-data)
  388. "Returns an object of type @code{statprof-stats}."
  389. ;; returns (vector proc-name
  390. ;; %-time-in-proc
  391. ;; cum-seconds-in-proc
  392. ;; self-seconds-in-proc
  393. ;; num-calls
  394. ;; self-secs-per-call
  395. ;; total-secs-per-call)
  396. (let* ((proc-name (call-data-printable call-data))
  397. (self-samples (call-data-self-sample-count call-data))
  398. (cum-samples (call-data-cum-sample-count call-data))
  399. (all-samples (statprof-sample-count))
  400. (secs-per-sample (/ (statprof-accumulated-time)
  401. (statprof-sample-count)))
  402. (num-calls (and %count-calls? (statprof-call-data-calls call-data))))
  403. (vector proc-name
  404. (* (/ self-samples all-samples) 100.0)
  405. (* cum-samples secs-per-sample 1.0)
  406. (* self-samples secs-per-sample 1.0)
  407. num-calls
  408. (and num-calls ;; maybe we only sampled in children
  409. (if (zero? self-samples) 0.0
  410. (/ (* self-samples secs-per-sample) 1.0 num-calls)))
  411. (and num-calls ;; cum-samples must be positive
  412. (/ (* cum-samples secs-per-sample)
  413. 1.0
  414. ;; num-calls might be 0 if we entered statprof during the
  415. ;; dynamic extent of the call
  416. (max num-calls 1))))))
  417. (define (statprof-stats-proc-name stats) (vector-ref stats 0))
  418. (define (statprof-stats-%-time-in-proc stats) (vector-ref stats 1))
  419. (define (statprof-stats-cum-secs-in-proc stats) (vector-ref stats 2))
  420. (define (statprof-stats-self-secs-in-proc stats) (vector-ref stats 3))
  421. (define (statprof-stats-calls stats) (vector-ref stats 4))
  422. (define (statprof-stats-self-secs-per-call stats) (vector-ref stats 5))
  423. (define (statprof-stats-cum-secs-per-call stats) (vector-ref stats 6))
  424. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  425. (define (stats-sorter x y)
  426. (let ((diff (- (statprof-stats-self-secs-in-proc x)
  427. (statprof-stats-self-secs-in-proc y))))
  428. (positive?
  429. (if (= diff 0)
  430. (- (statprof-stats-cum-secs-in-proc x)
  431. (statprof-stats-cum-secs-in-proc y))
  432. diff))))
  433. (define (statprof-display . port)
  434. "Displays a gprof-like summary of the statistics collected. Unless an
  435. optional @var{port} argument is passed, uses the current output port."
  436. (if (null? port) (set! port (current-output-port)))
  437. (cond
  438. ((zero? (statprof-sample-count))
  439. (format port "No samples recorded.\n"))
  440. (else
  441. (let* ((stats-list (statprof-fold-call-data
  442. (lambda (data prior-value)
  443. (cons (statprof-call-data->stats data)
  444. prior-value))
  445. '()))
  446. (sorted-stats (sort stats-list stats-sorter)))
  447. (define (display-stats-line stats)
  448. (if %count-calls?
  449. (format port "~6,2f ~9,2f ~9,2f ~7d ~8,2f ~8,2f "
  450. (statprof-stats-%-time-in-proc stats)
  451. (statprof-stats-cum-secs-in-proc stats)
  452. (statprof-stats-self-secs-in-proc stats)
  453. (statprof-stats-calls stats)
  454. (* 1000 (statprof-stats-self-secs-per-call stats))
  455. (* 1000 (statprof-stats-cum-secs-per-call stats)))
  456. (format port "~6,2f ~9,2f ~9,2f "
  457. (statprof-stats-%-time-in-proc stats)
  458. (statprof-stats-cum-secs-in-proc stats)
  459. (statprof-stats-self-secs-in-proc stats)))
  460. (display (statprof-stats-proc-name stats) port)
  461. (newline port))
  462. (if %count-calls?
  463. (begin
  464. (format port "~5a ~10a ~7a ~8a ~8a ~8a ~8@a\n"
  465. "% " "cumulative" "self" "" "self" "total" "")
  466. (format port "~5a ~9a ~8a ~8a ~8a ~8a ~8@a\n"
  467. "time" "seconds" "seconds" "calls" "ms/call" "ms/call" "name"))
  468. (begin
  469. (format port "~5a ~10a ~7a ~8@a\n"
  470. "%" "cumulative" "self" "")
  471. (format port "~5a ~10a ~7a ~8@a\n"
  472. "time" "seconds" "seconds" "name")))
  473. (for-each display-stats-line sorted-stats)
  474. (display "---\n" port)
  475. (simple-format #t "Sample count: ~A\n" (statprof-sample-count))
  476. (simple-format #t "Total time: ~A seconds (~A seconds in GC)\n"
  477. (statprof-accumulated-time)
  478. (/ gc-time-taken 1.0 internal-time-units-per-second))))))
  479. (define (statprof-display-anomolies)
  480. "A sanity check that attempts to detect anomolies in statprof's
  481. statistics.@code{}"
  482. (statprof-fold-call-data
  483. (lambda (data prior-value)
  484. (if (and %count-calls?
  485. (zero? (call-data-call-count data))
  486. (positive? (call-data-cum-sample-count data)))
  487. (simple-format #t
  488. "==[~A ~A ~A]\n"
  489. (call-data-name data)
  490. (call-data-call-count data)
  491. (call-data-cum-sample-count data))))
  492. #f)
  493. (simple-format #t "Total time: ~A\n" (statprof-accumulated-time))
  494. (simple-format #t "Sample count: ~A\n" (statprof-sample-count)))
  495. (define (statprof-accumulated-time)
  496. "Returns the time accumulated during the last statprof run.@code{}"
  497. (if (positive? profile-level)
  498. (error "Can't get accumulated time while profiler is running."))
  499. (/ accumulated-time internal-time-units-per-second))
  500. (define (statprof-sample-count)
  501. "Returns the number of samples taken during the last statprof run.@code{}"
  502. (if (positive? profile-level)
  503. (error "Can't get accumulated time while profiler is running."))
  504. sample-count)
  505. (define statprof-call-data-name call-data-name)
  506. (define statprof-call-data-calls call-data-call-count)
  507. (define statprof-call-data-cum-samples call-data-cum-sample-count)
  508. (define statprof-call-data-self-samples call-data-self-sample-count)
  509. (define (statprof-fetch-stacks)
  510. "Returns a list of stacks, as they were captured since the last call
  511. to @code{statprof-reset}.
  512. Note that stacks are only collected if the @var{full-stacks?} argument
  513. to @code{statprof-reset} is true."
  514. stacks)
  515. (define procedure=?
  516. (lambda (a b)
  517. (cond
  518. ((eq? a b))
  519. ((and (program? a) (program? b))
  520. (eq? (program-objcode a) (program-objcode b)))
  521. (else
  522. #f))))
  523. ;; tree ::= (car n . tree*)
  524. (define (lists->trees lists equal?)
  525. (let lp ((in lists) (n-terminal 0) (tails '()))
  526. (cond
  527. ((null? in)
  528. (let ((trees (map (lambda (tail)
  529. (cons (car tail)
  530. (lists->trees (cdr tail) equal?)))
  531. tails)))
  532. (cons (apply + n-terminal (map cadr trees))
  533. (sort trees
  534. (lambda (a b) (> (cadr a) (cadr b)))))))
  535. ((null? (car in))
  536. (lp (cdr in) (1+ n-terminal) tails))
  537. ((find (lambda (x) (equal? (car x) (caar in)))
  538. tails)
  539. => (lambda (tail)
  540. (lp (cdr in)
  541. n-terminal
  542. (assq-set! tails
  543. (car tail)
  544. (cons (cdar in) (cdr tail))))))
  545. (else
  546. (lp (cdr in)
  547. n-terminal
  548. (acons (caar in) (list (cdar in)) tails))))))
  549. (define (stack->procedures stack)
  550. (filter identity
  551. (unfold-right (lambda (x) (not x))
  552. frame-procedure
  553. frame-previous
  554. (stack-ref stack 0))))
  555. (define (statprof-fetch-call-tree)
  556. "Return a call tree for the previous statprof run.
  557. The return value is a list of nodes, each of which is of the type:
  558. @code
  559. node ::= (@var{proc} @var{count} . @var{nodes})
  560. @end code"
  561. (cons #t (lists->trees (map stack->procedures stacks) procedure=?)))
  562. (define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
  563. (full-stacks? #f))
  564. "Profiles the execution of @var{thunk}.
  565. The stack will be sampled @var{hz} times per second, and the thunk itself will
  566. be called @var{loop} times.
  567. If @var{count-calls?} is true, all procedure calls will be recorded. This
  568. operation is somewhat expensive.
  569. If @var{full-stacks?} is true, at each sample, statprof will store away the
  570. whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
  571. @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
  572. (dynamic-wind
  573. (lambda ()
  574. (statprof-reset (inexact->exact (floor (/ 1 hz)))
  575. (inexact->exact (* 1e6 (- (/ 1 hz)
  576. (floor (/ 1 hz)))))
  577. count-calls?
  578. full-stacks?)
  579. (statprof-start))
  580. (lambda ()
  581. (let lp ((i loop))
  582. (if (not (zero? i))
  583. (begin
  584. (thunk)
  585. (lp (1- i))))))
  586. (lambda ()
  587. (statprof-stop)
  588. (statprof-display)
  589. (set! procedure-data #f))))
  590. (define-macro (with-statprof . args)
  591. "Profiles the expressions in its body.
  592. Keyword arguments:
  593. @table @code
  594. @item #:loop
  595. Execute the body @var{loop} number of times, or @code{#f} for no looping
  596. default: @code{#f}
  597. @item #:hz
  598. Sampling rate
  599. default: @code{20}
  600. @item #:count-calls?
  601. Whether to instrument each function call (expensive)
  602. default: @code{#f}
  603. @item #:full-stacks?
  604. Whether to collect away all sampled stacks into a list
  605. default: @code{#f}
  606. @end table"
  607. (define (kw-arg-ref kw args def)
  608. (cond
  609. ((null? args) (error "Invalid macro body"))
  610. ((keyword? (car args))
  611. (if (eq? (car args) kw)
  612. (cadr args)
  613. (kw-arg-ref kw (cddr args) def)))
  614. ((eq? kw #f def) ;; asking for the body
  615. args)
  616. (else def))) ;; kw not found
  617. `((@ (statprof) statprof)
  618. (lambda () ,@(kw-arg-ref #f args #f))
  619. #:loop ,(kw-arg-ref #:loop args 1)
  620. #:hz ,(kw-arg-ref #:hz args 100)
  621. #:count-calls? ,(kw-arg-ref #:count-calls? args #f)
  622. #:full-stacks? ,(kw-arg-ref #:full-stacks? args #f)))
  623. (define* (gcprof thunk #:key (loop 1) (full-stacks? #f))
  624. "Do an allocation profile of the execution of @var{thunk}.
  625. The stack will be sampled soon after every garbage collection, yielding
  626. an approximate idea of what is causing allocation in your program.
  627. Since GC does not occur very frequently, you may need to use the
  628. @var{loop} parameter, to cause @var{thunk} to be called @var{loop}
  629. times.
  630. If @var{full-stacks?} is true, at each sample, statprof will store away the
  631. whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
  632. @code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
  633. (define (reset)
  634. (if (positive? profile-level)
  635. (error "Can't reset profiler while profiler is running."))
  636. (set! accumulated-time 0)
  637. (set! last-start-time #f)
  638. (set! sample-count 0)
  639. (set! %count-calls? #f)
  640. (set! procedure-data (make-hash-table 131))
  641. (set! record-full-stacks? full-stacks?)
  642. (set! stacks '()))
  643. (define (gc-callback)
  644. (cond
  645. (inside-profiler?)
  646. (else
  647. (set! inside-profiler? #t)
  648. ;; FIXME: should be able to set an outer frame for the stack cut
  649. (let ((stop-time (get-internal-run-time))
  650. ;; Cut down to gc-callback, and then one before (the
  651. ;; after-gc async). See the note in profile-signal-handler
  652. ;; also.
  653. (stack (or (make-stack #t gc-callback 0 1)
  654. (pk 'what! (make-stack #t)))))
  655. (sample-stack-procs stack)
  656. (accumulate-time stop-time)
  657. (set! last-start-time (get-internal-run-time)))
  658. (set! inside-profiler? #f))))
  659. (define (start)
  660. (set! profile-level (+ profile-level 1))
  661. (if (= profile-level 1)
  662. (begin
  663. (set! remaining-prof-time #f)
  664. (set! last-start-time (get-internal-run-time))
  665. (set! gc-time-taken (cdr (assq 'gc-time-taken (gc-stats))))
  666. (add-hook! after-gc-hook gc-callback)
  667. (set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
  668. #t)))
  669. (define (stop)
  670. (set! profile-level (- profile-level 1))
  671. (if (zero? profile-level)
  672. (begin
  673. (set! gc-time-taken
  674. (- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
  675. (remove-hook! after-gc-hook gc-callback)
  676. (accumulate-time (get-internal-run-time))
  677. (set! last-start-time #f))))
  678. (dynamic-wind
  679. (lambda ()
  680. (reset)
  681. (start))
  682. (lambda ()
  683. (let lp ((i loop))
  684. (if (not (zero? i))
  685. (begin
  686. (thunk)
  687. (lp (1- i))))))
  688. (lambda ()
  689. (stop)
  690. (statprof-display)
  691. (set! procedure-data #f))))