statprof.scm 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. ;;;; (statprof) -- a statistical profiler for Guile
  2. ;;;; -*-scheme-*-
  3. ;;;;
  4. ;;;; Copyright (C) 2009, 2010, 2011, 2013-2018, 2020 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 a statistical profiler for Guile. See the
  25. ;;; "Statprof" section in the manual, for more information.
  26. ;;;
  27. ;;; Code:
  28. (define-module (statprof)
  29. #:use-module (srfi srfi-1)
  30. #:use-module (srfi srfi-9)
  31. #:use-module (srfi srfi-9 gnu)
  32. #:use-module (ice-9 format)
  33. #:use-module (ice-9 match)
  34. #:use-module (ice-9 vlist)
  35. #:use-module (system vm vm)
  36. #:use-module (system vm frame)
  37. #:use-module (system vm debug)
  38. #:use-module (system vm program)
  39. #:export (statprof-active?
  40. statprof-start
  41. statprof-stop
  42. statprof-reset
  43. statprof-accumulated-time
  44. statprof-sample-count
  45. statprof-fold-call-data
  46. statprof-proc-call-data
  47. statprof-call-data-name
  48. statprof-call-data-calls
  49. statprof-call-data-cum-samples
  50. statprof-call-data-self-samples
  51. statprof-call-data->stats
  52. statprof-stats-proc-name
  53. statprof-stats-proc-source
  54. statprof-stats-%-time-in-proc
  55. statprof-stats-cum-secs-in-proc
  56. statprof-stats-self-secs-in-proc
  57. statprof-stats-calls
  58. statprof-stats-self-secs-per-call
  59. statprof-stats-cum-secs-per-call
  60. statprof-display
  61. statprof-display-anomalies
  62. statprof-fetch-stacks
  63. statprof-fetch-call-tree
  64. statprof
  65. gcprof))
  66. ;;; ~ Implementation notes ~
  67. ;;;
  68. ;;; Statprof can be divided into two pieces: data collection and data
  69. ;;; analysis.
  70. ;;;
  71. ;;; The data collection runs concurrently with the program, and is
  72. ;;; designed to be as cheap as possible. The main data collection
  73. ;;; instrument is the stack sampler, driven by SIGPROF signals that are
  74. ;;; scheduled with periodic setitimer calls. The stack sampler simply
  75. ;;; looks at every frame on the stack, and writes a representation of
  76. ;;; the frame's procedure into a growable buffer.
  77. ;;;
  78. ;;; For most frames, this representation is the instruction pointer of
  79. ;;; that frame, because it's cheap to get and you can map from
  80. ;;; instruction pointer to procedure fairly cheaply. This won't
  81. ;;; distinguish between different closures which share the same code,
  82. ;;; but that is usually what we want anyway.
  83. ;;;
  84. ;;; The other part of data collection is the exact call counter, which
  85. ;;; uses the VM's "apply" hook to record each procedure call.
  86. ;;; Naturally, this is quite expensive, and it is off by default.
  87. ;;; Running code at every procedure call effectively penalizes procedure
  88. ;;; calls. Still, it's useful sometimes. If the profiler state has a
  89. ;;; call-counts table, then calls will be counted. As with the stack
  90. ;;; counter, the key in the hash table is the code pointer of the
  91. ;;; procedure being called. The call counter can also see calls of
  92. ;;; non-programs, for example in the case of applicable structs. In
  93. ;;; that case the key is the procedure itself.
  94. ;;;
  95. ;;; After collection is finished, the data can be analyzed. The first
  96. ;;; step is usually to run over the stack traces, tabulating sample
  97. ;;; counts by procedure; the stack-samples->procedure-data does that.
  98. ;;; The result of stack-samples->procedure-data is a hash table mapping
  99. ;;; procedures to "call data" records. The call data values are exposed
  100. ;;; to users via the statprof-fold-call-data procedure.
  101. ;;;
  102. ;;; Usually all the analysis is triggered by calling statprof-display,
  103. ;;; or having the statprof procedure call it for you.
  104. ;;;
  105. ;;; The other thing we can do is to look at the stacks themselves, for
  106. ;;; example via statprof-fetch-call-tree.
  107. ;;;
  108. ;;; ~ Threads and state ~
  109. ;;;
  110. ;;; The state of the profiler is contained in a <state> record, which is
  111. ;;; bound to a thread-local parameter. The accurate call counter uses
  112. ;;; the VM apply hook, which is also local to the current thread, so all
  113. ;;; is good there.
  114. ;;;
  115. ;;; The problem comes in the statistical stack sampler's use of
  116. ;;; `setitimer' and SIGPROF. The timer manipulated by setitimer is a
  117. ;;; whole-process timer, so it decrements as other threads execute,
  118. ;;; which is the wrong thing if you want to profile just one thread. On
  119. ;;; the other hand, SIGPROF is delivered to the process as a whole,
  120. ;;; which is fine given Guile's signal-handling thread, but then only
  121. ;;; delivered to the thread running statprof, which isn't the right
  122. ;;; thing if you want to profile the whole system.
  123. ;;;
  124. ;;; The summary is that statprof works more or less well as a per-thread
  125. ;;; profiler if no other threads are running on their own when
  126. ;;; profiling. If the other threads are running on behalf of the thread
  127. ;;; being profiled (as via futures or parallel marking) things still
  128. ;;; mostly work as expected. You can run statprof in one thread,
  129. ;;; finish, and then run statprof in another thread, and the profile
  130. ;;; runs won't affect each other. But if you want true per-thread
  131. ;;; profiles when other things are happening in the process, including
  132. ;;; other statprof runs, or whole-process profiles with per-thread
  133. ;;; breakdowns, the use of setitimer currently prevents that.
  134. ;;;
  135. ;;; The solution would be to switch to POSIX.1-2001's timer_create(2),
  136. ;;; and to add some more threading-related API to statprof. Some other
  137. ;;; day.
  138. ;;;
  139. (define-record-type <state>
  140. (make-state accumulated-time last-start-time sample-count
  141. sampling-period remaining-prof-time profile-level
  142. call-counts gc-time-taken inside-profiler?
  143. prev-sigprof-handler outer-cut buffer buffer-pos)
  144. state?
  145. ;; Total time so far.
  146. (accumulated-time accumulated-time set-accumulated-time!)
  147. ;; Start-time when timer is active.
  148. (last-start-time last-start-time set-last-start-time!)
  149. ;; Total count of sampler calls.
  150. (sample-count sample-count set-sample-count!)
  151. ;; Microseconds.
  152. (sampling-period sampling-period set-sampling-period!)
  153. ;; Time remaining when prof suspended.
  154. (remaining-prof-time remaining-prof-time set-remaining-prof-time!)
  155. ;; For user start/stop nesting.
  156. (profile-level profile-level set-profile-level!)
  157. ;; Hash table mapping ip -> call count, or #f if not counting calls.
  158. (call-counts call-counts set-call-counts!)
  159. ;; GC time between statprof-start and statprof-stop.
  160. (gc-time-taken gc-time-taken set-gc-time-taken!)
  161. ;; True if we are inside the profiler.
  162. (inside-profiler? inside-profiler? set-inside-profiler?!)
  163. ;; Previous sigprof handler.
  164. (prev-sigprof-handler prev-sigprof-handler set-prev-sigprof-handler!)
  165. ;; Outer stack cut, or 0.
  166. (outer-cut outer-cut)
  167. ;; Stack samples.
  168. (buffer buffer set-buffer!)
  169. (buffer-pos buffer-pos set-buffer-pos!))
  170. (define profiler-state (make-parameter #f))
  171. (define (fresh-buffer)
  172. (make-vector 1024 #f))
  173. (define (expand-buffer buf)
  174. (let* ((size (vector-length buf))
  175. (new (make-vector (* size 2) #f)))
  176. (vector-move-left! buf 0 (vector-length buf) new 0)
  177. new))
  178. (define* (fresh-profiler-state #:key (count-calls? #f)
  179. (sampling-period 10000)
  180. (outer-cut 0))
  181. (make-state 0 #f 0
  182. sampling-period 0 0
  183. (and count-calls? (make-hash-table)) 0 #f
  184. #f outer-cut (fresh-buffer) 0))
  185. (define (ensure-profiler-state)
  186. (or (profiler-state)
  187. (let ((state (fresh-profiler-state)))
  188. (profiler-state state)
  189. state)))
  190. (define (existing-profiler-state)
  191. (or (profiler-state)
  192. (error "expected there to be a profiler state")))
  193. (define (accumulate-time state stop-time)
  194. (set-accumulated-time! state
  195. (+ (accumulated-time state)
  196. (- stop-time (last-start-time state)))))
  197. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  198. ;; SIGPROF handler
  199. (define (sample-stack-procs state stack)
  200. (set-sample-count! state (+ (sample-count state) 1))
  201. (let lp ((frame (stack-ref stack 0))
  202. (len (stack-length stack))
  203. (buffer (buffer state))
  204. (pos (buffer-pos state)))
  205. (define (write-sample sample)
  206. (vector-set! buffer pos sample))
  207. (define (continue pos)
  208. (lp (frame-previous frame) (1- len) buffer pos))
  209. (define (write-sample-and-continue sample)
  210. (write-sample sample)
  211. (continue (1+ pos)))
  212. (cond
  213. ((= pos (vector-length buffer))
  214. (lp frame len (expand-buffer buffer) pos))
  215. ((or (zero? len) (not frame))
  216. (write-sample #f)
  217. (set-buffer! state buffer)
  218. (set-buffer-pos! state (1+ pos)))
  219. (else
  220. (write-sample-and-continue (frame-instruction-pointer frame))))))
  221. (define (reset-sigprof-timer usecs)
  222. ;; Guile's setitimer binding is terrible.
  223. (let ((prev (setitimer ITIMER_PROF 0 0 0 usecs)))
  224. (+ (* (caadr prev) #e1e6) (cdadr prev))))
  225. (define profile-signal-handler
  226. (let ()
  227. (define (profile-signal-handler sig)
  228. (define state (existing-profiler-state))
  229. (set-inside-profiler?! state #t)
  230. (when (positive? (profile-level state))
  231. (let* ((stop-time (get-internal-run-time))
  232. ;; Cut down to the signal handler. Note that this will
  233. ;; only work if statprof.scm is compiled; otherwise we
  234. ;; get `eval' on the stack instead, because if it's not
  235. ;; compiled, profile-signal-handler is a thunk that
  236. ;; tail-calls eval. For the same reason we define the
  237. ;; handler in an inner letrec, so that the compiler sees
  238. ;; the inner reference to profile-signal-handler as the
  239. ;; same as the procedure, and therefore keeps slot 0
  240. ;; alive. Nastiness, that. Finally we cut one more
  241. ;; inner frame, corresponding to the handle-interrupts
  242. ;; trampoline.
  243. (stack
  244. (or (make-stack #t profile-signal-handler (outer-cut state) 1)
  245. (pk 'what! (make-stack #t)))))
  246. (sample-stack-procs state stack)
  247. (accumulate-time state stop-time)
  248. (set-last-start-time! state (get-internal-run-time))
  249. (reset-sigprof-timer (sampling-period state))))
  250. (set-inside-profiler?! state #f))
  251. profile-signal-handler))
  252. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  253. ;; Count total calls.
  254. (define (count-call frame)
  255. (let ((state (existing-profiler-state)))
  256. (unless (inside-profiler? state)
  257. (let* ((key (frame-instruction-pointer frame))
  258. (handle (hashv-create-handle! (call-counts state) key 0)))
  259. (set-cdr! handle (1+ (cdr handle)))))))
  260. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  261. (define (statprof-active?)
  262. "Returns @code{#t} if @code{statprof-start} has been called more times
  263. than @code{statprof-stop}, @code{#f} otherwise."
  264. (define state (profiler-state))
  265. (and state (positive? (profile-level state))))
  266. ;; Do not call this from statprof internal functions -- user only.
  267. (define* (statprof-start #:optional (state (ensure-profiler-state)))
  268. "Start the profiler.@code{}"
  269. ;; After some head-scratching, I don't *think* I need to mask/unmask
  270. ;; signals here, but if I'm wrong, please let me know.
  271. (set-profile-level! state (+ (profile-level state) 1))
  272. (when (= (profile-level state) 1)
  273. (let ((rpt (remaining-prof-time state)))
  274. (set-remaining-prof-time! state 0)
  275. ;; FIXME: Use per-thread run time.
  276. (set-last-start-time! state (get-internal-run-time))
  277. (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
  278. (let ((prev (sigaction SIGPROF profile-signal-handler)))
  279. (set-prev-sigprof-handler! state (car prev)))
  280. (reset-sigprof-timer (if (zero? rpt) (sampling-period state) rpt))
  281. (when (call-counts state)
  282. (vm-add-apply-hook! count-call)
  283. (set-vm-trace-level! (1+ (vm-trace-level))))
  284. #t)))
  285. ;; Do not call this from statprof internal functions -- user only.
  286. (define* (statprof-stop #:optional (state (ensure-profiler-state)))
  287. "Stop the profiler.@code{}"
  288. ;; After some head-scratching, I don't *think* I need to mask/unmask
  289. ;; signals here, but if I'm wrong, please let me know.
  290. (set-profile-level! state (- (profile-level state) 1))
  291. (when (zero? (profile-level state))
  292. (when (call-counts state)
  293. (set-vm-trace-level! (1- (vm-trace-level)))
  294. (vm-remove-apply-hook! count-call))
  295. (set-gc-time-taken! state
  296. (- (assq-ref (gc-stats) 'gc-time-taken)
  297. (gc-time-taken state)))
  298. ;; I believe that we need to do this before getting the time
  299. ;; (unless we want to make things even more complicated).
  300. (set-remaining-prof-time! state (reset-sigprof-timer 0))
  301. (accumulate-time state (get-internal-run-time))
  302. (sigaction SIGPROF (prev-sigprof-handler state))
  303. (set-prev-sigprof-handler! state #f)
  304. (set-last-start-time! state #f)))
  305. (define* (statprof-reset sample-seconds sample-microseconds count-calls?
  306. #:optional full-stacks?)
  307. "Reset the statprof sampler interval to @var{sample-seconds} and
  308. @var{sample-microseconds}. If @var{count-calls?} is true, arrange to
  309. instrument procedure calls as well as collecting statistical profiling
  310. data. (The optional @var{full-stacks?} argument is deprecated; statprof
  311. always collects full stacks.)"
  312. (when (statprof-active?)
  313. (error "Can't reset profiler while profiler is running."))
  314. (profiler-state
  315. (fresh-profiler-state #:count-calls? count-calls?
  316. #:sampling-period (+ (* sample-seconds #e1e6)
  317. sample-microseconds)))
  318. (values))
  319. (define-record-type call-data
  320. (make-call-data name printable source
  321. call-count cum-sample-count self-sample-count)
  322. call-data?
  323. (name call-data-name)
  324. (printable call-data-printable)
  325. (source call-data-source)
  326. (call-count call-data-call-count set-call-data-call-count!)
  327. (cum-sample-count call-data-cum-sample-count set-call-data-cum-sample-count!)
  328. (self-sample-count call-data-self-sample-count set-call-data-self-sample-count!))
  329. (define (source->string source)
  330. (format #f "~a:~a:~a"
  331. (or (source-file source) "<current input>")
  332. (source-line-for-user source)
  333. (source-column source)))
  334. (define (addr->pdi addr cache)
  335. (cond
  336. ((hashv-get-handle cache addr) => cdr)
  337. (else
  338. (let ((data (find-program-debug-info addr)))
  339. (hashv-set! cache addr data)
  340. data))))
  341. (define (addr->printable addr pdi)
  342. (or (and=> (and=> pdi program-debug-info-name) symbol->string)
  343. (and=> (primitive-code-name addr) symbol->string)
  344. (string-append "anon #x" (number->string addr 16))))
  345. (define (inc-call-data-cum-sample-count! cd)
  346. (set-call-data-cum-sample-count! cd (1+ (call-data-cum-sample-count cd))))
  347. (define (inc-call-data-self-sample-count! cd)
  348. (set-call-data-self-sample-count! cd (1+ (call-data-self-sample-count cd))))
  349. (define (skip-count-call buffer start len)
  350. ;; If we are counting all procedure calls, count-call might be on the
  351. ;; stack. If it is, skip that part of the stack.
  352. (match (program-address-range count-call)
  353. ((lo . hi)
  354. (let lp ((pos start))
  355. (if (< pos len)
  356. (let ((key (vector-ref buffer pos)))
  357. (cond
  358. ((not key)
  359. ;; End of stack; count-call not on the stack.
  360. start)
  361. ((and (number? key) (<= lo key) (< key hi))
  362. ;; Found count-call.
  363. (1+ pos))
  364. (else
  365. ;; Otherwise keep going.
  366. (lp (1+ pos)))))
  367. start)))))
  368. (define (stack-samples->procedure-data state)
  369. (let ((table (make-hash-table))
  370. (addr-cache (make-hash-table))
  371. (call-counts (call-counts state))
  372. (buffer (buffer state))
  373. (len (buffer-pos state)))
  374. (define (addr->call-data addr)
  375. (let* ((pdi (addr->pdi addr addr-cache))
  376. (entry (if pdi (program-debug-info-addr pdi) addr)))
  377. (or (hashv-ref table entry)
  378. (let ((data (make-call-data (and=> pdi program-debug-info-name)
  379. (addr->printable entry pdi)
  380. (find-source-for-addr entry)
  381. (and call-counts
  382. (hashv-ref call-counts entry))
  383. 0
  384. 0)))
  385. (hashv-set! table entry data)
  386. data))))
  387. (when call-counts
  388. (hash-for-each (lambda (callee count)
  389. (unless (number? callee)
  390. (error "unexpected callee" callee))
  391. (addr->call-data callee))
  392. call-counts))
  393. (let visit-stacks ((pos 0))
  394. (cond
  395. ((< pos len)
  396. (let ((pos (if call-counts
  397. (skip-count-call buffer pos len)
  398. pos)))
  399. (inc-call-data-self-sample-count!
  400. (addr->call-data (vector-ref buffer pos)))
  401. (let visit-stack ((pos pos))
  402. (cond
  403. ((vector-ref buffer pos)
  404. => (lambda (ip)
  405. (inc-call-data-cum-sample-count! (addr->call-data ip))
  406. (visit-stack (1+ pos))))
  407. (else
  408. (visit-stacks (1+ pos)))))))
  409. (else table)))))
  410. (define (stack-samples->callee-lists state)
  411. (let ((buffer (buffer state))
  412. (len (buffer-pos state)))
  413. (let visit-stacks ((pos 0) (out '()))
  414. (cond
  415. ((< pos len)
  416. (let visit-stack ((pos (if (call-counts state)
  417. (skip-count-call buffer pos len)
  418. pos))
  419. (stack '()))
  420. (cond
  421. ((vector-ref buffer pos)
  422. => (lambda (callee)
  423. (visit-stack (1+ pos) (cons callee stack))))
  424. (else
  425. (visit-stacks (1+ pos) (cons (reverse stack) out))))))
  426. (else (reverse out))))))
  427. (define* (statprof-fold-call-data proc init #:optional
  428. (state (existing-profiler-state)))
  429. "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
  430. called while statprof is active. @var{proc} should take two arguments,
  431. @code{(@var{call-data} @var{prior-result})}.
  432. Note that a given proc-name may appear multiple times, but if it does,
  433. it represents different functions with the same name."
  434. (when (statprof-active?)
  435. (error "Can't call statprof-fold-call-data while profiler is running."))
  436. (hash-fold
  437. (lambda (key value prior-result)
  438. (proc value prior-result))
  439. init
  440. (stack-samples->procedure-data state)))
  441. (define* (statprof-proc-call-data proc #:optional
  442. (state (existing-profiler-state)))
  443. "Returns the call-data associated with @var{proc}, or @code{#f} if
  444. none is available."
  445. (when (statprof-active?)
  446. (error "Can't call statprof-proc-call-data while profiler is running."))
  447. (unless (program? proc)
  448. (error "statprof-call-data only works for VM programs"))
  449. (hashv-ref (stack-samples->procedure-data state) (program-code proc)))
  450. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  451. ;; Stats
  452. (define-record-type stats
  453. (make-stats proc-name proc-source
  454. %-time-in-proc cum-secs-in-proc self-secs-in-proc
  455. calls)
  456. stats?
  457. (proc-name statprof-stats-proc-name)
  458. (proc-source statprof-stats-proc-source)
  459. (%-time-in-proc statprof-stats-%-time-in-proc)
  460. (cum-secs-in-proc statprof-stats-cum-secs-in-proc)
  461. (self-secs-in-proc statprof-stats-self-secs-in-proc)
  462. (calls statprof-stats-calls))
  463. (define (statprof-stats-self-secs-per-call stats)
  464. (let ((calls (statprof-stats-calls stats)))
  465. (and calls
  466. (/ (statprof-stats-self-secs-in-proc stats)
  467. calls))))
  468. (define (statprof-stats-cum-secs-per-call stats)
  469. (let ((calls (statprof-stats-calls stats)))
  470. (and calls
  471. (/ (statprof-stats-cum-secs-in-proc stats)
  472. ;; `calls' might be 0 if we entered statprof during the
  473. ;; dynamic extent of the call.
  474. (max calls 1)))))
  475. (define (statprof-call-data->stats call-data)
  476. "Returns an object of type @code{statprof-stats}."
  477. (define state (existing-profiler-state))
  478. (let* ((proc-name (call-data-name call-data))
  479. (proc-source (and=> (call-data-source call-data) source->string))
  480. (self-samples (call-data-self-sample-count call-data))
  481. (cum-samples (call-data-cum-sample-count call-data))
  482. (all-samples (statprof-sample-count state))
  483. (secs-per-sample (/ (statprof-accumulated-time state)
  484. (statprof-sample-count state)))
  485. (num-calls (and (call-counts state)
  486. (statprof-call-data-calls call-data))))
  487. (make-stats (or proc-name
  488. ;; If there is no name and no source, fall back to
  489. ;; printable.
  490. (and (not proc-source) (call-data-printable call-data)))
  491. proc-source
  492. (* (/ self-samples all-samples) 100.0)
  493. (* cum-samples secs-per-sample 1.0)
  494. (* self-samples secs-per-sample 1.0)
  495. num-calls)))
  496. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  497. (define (stats-sorter x y)
  498. (let ((diff (- (statprof-stats-self-secs-in-proc x)
  499. (statprof-stats-self-secs-in-proc y))))
  500. (positive?
  501. (if (= diff 0)
  502. (- (statprof-stats-cum-secs-in-proc x)
  503. (statprof-stats-cum-secs-in-proc y))
  504. diff))))
  505. (define* (statprof-display/flat port state)
  506. "Displays a gprof-like summary of the statistics collected. Unless an
  507. optional @var{port} argument is passed, uses the current output port."
  508. (cond
  509. ((zero? (statprof-sample-count state))
  510. (format port "No samples recorded.\n"))
  511. (else
  512. (let* ((stats-list (statprof-fold-call-data
  513. (lambda (data prior-value)
  514. (cons (statprof-call-data->stats data)
  515. prior-value))
  516. '()
  517. state))
  518. (sorted-stats (sort stats-list stats-sorter)))
  519. (define (display-stats-line stats)
  520. (format port "~6,2f ~9,2f ~9,2f"
  521. (statprof-stats-%-time-in-proc stats)
  522. (statprof-stats-cum-secs-in-proc stats)
  523. (statprof-stats-self-secs-in-proc stats))
  524. (if (call-counts state)
  525. (if (statprof-stats-calls stats)
  526. (format port " ~7d "
  527. (statprof-stats-calls stats))
  528. (format port " "))
  529. (display " " port))
  530. (let ((source (statprof-stats-proc-source stats))
  531. (name (statprof-stats-proc-name stats)))
  532. (when source
  533. (display source port)
  534. (when name
  535. (display ":" port)))
  536. (when name
  537. (display name port))
  538. (newline port)))
  539. (if (call-counts state)
  540. (begin
  541. (format port "~5a ~10a ~7a ~8a\n"
  542. "% " "cumulative" "self" "")
  543. (format port "~5a ~9a ~8a ~7a ~a\n"
  544. "time" "seconds" "seconds" "calls" "procedure"))
  545. (begin
  546. (format port "~5a ~10a ~7a ~8a\n"
  547. "%" "cumulative" "self" "")
  548. (format port "~5a ~10a ~7a ~a\n"
  549. "time" "seconds" "seconds" "procedure")))
  550. (for-each display-stats-line sorted-stats)
  551. (display "---\n" port)
  552. (format port "Sample count: ~A\n" (statprof-sample-count state))
  553. (format port "Total time: ~A seconds (~A seconds in GC)\n"
  554. (statprof-accumulated-time state)
  555. (/ (gc-time-taken state)
  556. 1.0 internal-time-units-per-second))))))
  557. (define* (statprof-display-anomalies #:optional (state
  558. (existing-profiler-state)))
  559. "A sanity check that attempts to detect anomalies in statprof's
  560. statistics.@code{}"
  561. (statprof-fold-call-data
  562. (lambda (data prior-value)
  563. (when (and (call-counts state)
  564. (zero? (call-data-call-count data))
  565. (positive? (call-data-cum-sample-count data)))
  566. (format #t
  567. "==[~A ~A ~A]\n"
  568. (call-data-name data)
  569. (call-data-call-count data)
  570. (call-data-cum-sample-count data))))
  571. #f
  572. state)
  573. (format #t "Total time: ~A\n" (statprof-accumulated-time state))
  574. (format #t "Sample count: ~A\n" (statprof-sample-count state)))
  575. (define* (statprof-accumulated-time #:optional (state
  576. (existing-profiler-state)))
  577. "Returns the time accumulated during the last statprof run.@code{}"
  578. (/ (accumulated-time state) 1.0 internal-time-units-per-second))
  579. (define* (statprof-sample-count #:optional (state (existing-profiler-state)))
  580. "Returns the number of samples taken during the last statprof run.@code{}"
  581. (sample-count state))
  582. (define statprof-call-data-name call-data-name)
  583. (define statprof-call-data-calls call-data-call-count)
  584. (define statprof-call-data-cum-samples call-data-cum-sample-count)
  585. (define statprof-call-data-self-samples call-data-self-sample-count)
  586. (define* (statprof-fetch-stacks #:optional (state (existing-profiler-state)))
  587. "Returns a list of stacks, as they were captured since the last call
  588. to @code{statprof-reset}."
  589. (stack-samples->callee-lists state))
  590. ;; tree ::= (car n . tree*)
  591. (define (lists->trees lists equal?)
  592. (let lp ((in lists) (n-terminal 0) (tails '()))
  593. (cond
  594. ((null? in)
  595. (let ((trees (map (lambda (tail)
  596. (cons (car tail)
  597. (lists->trees (cdr tail) equal?)))
  598. tails)))
  599. (cons (apply + n-terminal (map cadr trees))
  600. (sort trees
  601. (lambda (a b) (> (cadr a) (cadr b)))))))
  602. ((null? (car in))
  603. (lp (cdr in) (1+ n-terminal) tails))
  604. ((find (lambda (x) (equal? (car x) (caar in)))
  605. tails)
  606. => (lambda (tail)
  607. (lp (cdr in)
  608. n-terminal
  609. (assq-set! tails
  610. (car tail)
  611. (cons (cdar in) (cdr tail))))))
  612. (else
  613. (lp (cdr in)
  614. n-terminal
  615. (acons (caar in) (list (cdar in)) tails))))))
  616. (define (collect-cycles items)
  617. (define (find-cycle item stack)
  618. (match (vhash-assoc item stack)
  619. (#f #f)
  620. ((_ . pos)
  621. (let ((size (- (vlist-length stack) pos)))
  622. (and (<= (1- (* size 2)) (vlist-length stack))
  623. (let lp ((i 0))
  624. (if (= i (1- size))
  625. size
  626. (and (equal? (car (vlist-ref stack i))
  627. (car (vlist-ref stack (+ i size))))
  628. (lp (1+ i))))))))))
  629. (define (collect-cycle stack size)
  630. (vlist-fold-right (lambda (pair cycle)
  631. (cons (car pair) cycle))
  632. '()
  633. (vlist-take stack size)))
  634. (define (detect-cycle items stack)
  635. (match items
  636. (() stack)
  637. ((item . items)
  638. (let* ((cycle-size (find-cycle item stack)))
  639. (if cycle-size
  640. (chomp-cycles (collect-cycle stack cycle-size)
  641. items
  642. (vlist-drop stack (1- (* cycle-size 2))))
  643. (chomp-cycles (list item) items stack))))))
  644. (define (skip-cycles cycle items)
  645. (let lp ((a cycle) (b items))
  646. (match a
  647. (() (skip-cycles cycle b))
  648. ((a . a*)
  649. (match b
  650. (() items)
  651. ((b . b*)
  652. (if (equal? a b)
  653. (lp a* b*)
  654. items)))))))
  655. (define (chomp-cycles cycle items stack)
  656. (detect-cycle (skip-cycles cycle items)
  657. (vhash-cons (match cycle
  658. ((item) item)
  659. (cycle cycle))
  660. (vlist-length stack)
  661. stack)))
  662. (vlist-fold
  663. (lambda (pair out)
  664. (cons (car pair) out))
  665. '()
  666. (detect-cycle items vlist-null)))
  667. (define* (statprof-fetch-call-tree #:optional (state (existing-profiler-state))
  668. #:key precise?)
  669. "Return a call tree for the previous statprof run.
  670. The return value is a list of nodes, each of which is of the type:
  671. @code
  672. node ::= (@var{proc} @var{count} . @var{nodes})
  673. @end code"
  674. (define-syntax-rule (define-memoized (fn arg) body)
  675. (define fn
  676. (let ((table (make-hash-table)))
  677. (lambda (arg)
  678. (cond
  679. ((hash-get-handle table arg) => cdr)
  680. (else
  681. (let ((res body))
  682. (hash-set! table arg res)
  683. res)))))))
  684. (define-memoized (callee->printable callee)
  685. (cond
  686. ((number? callee)
  687. (let* ((pdi (find-program-debug-info callee))
  688. (name (or (and=> (and pdi (program-debug-info-name pdi))
  689. symbol->string)
  690. (string-append "#x" (number->string callee 16))))
  691. (loc (and=> (find-source-for-addr
  692. (or (and (not precise?)
  693. (and=> pdi program-debug-info-addr))
  694. callee))
  695. source->string)))
  696. (if loc
  697. (string-append name " at " loc)
  698. name)))
  699. (else
  700. (with-output-to-string (lambda () (write callee))))))
  701. (define (munge-stack stack)
  702. ;; We collect the sample in newest-to-oldest
  703. ;; order. Change to have the oldest first.
  704. (let ((stack (reverse stack)))
  705. (define (cycle->printable item)
  706. (if (string? item)
  707. item
  708. (string-join (map cycle->printable item) ", ")))
  709. (map cycle->printable (collect-cycles (map callee->printable stack)))))
  710. (let ((stacks (map munge-stack (stack-samples->callee-lists state))))
  711. (cons #t (lists->trees stacks equal?))))
  712. (define (statprof-display/tree port state)
  713. (match (statprof-fetch-call-tree state)
  714. ((#t total-count . trees)
  715. (define (print-tree tree indent)
  716. (define (print-subtree tree) (print-tree tree (+ indent 2)))
  717. (match tree
  718. ((callee count . trees)
  719. (format port "~vt~,1f% ~a\n" indent (* 100. (/ count total-count))
  720. callee)
  721. (for-each print-subtree trees))))
  722. (for-each (lambda (tree) (print-tree tree 0)) trees)))
  723. (display "---\n" port)
  724. (format port "Sample count: ~A\n" (statprof-sample-count state))
  725. (format port "Total time: ~A seconds (~A seconds in GC)\n"
  726. (statprof-accumulated-time state)
  727. (/ (gc-time-taken state)
  728. 1.0 internal-time-units-per-second)))
  729. (define* (statprof-display #:optional (port (current-output-port))
  730. (state (existing-profiler-state))
  731. #:key (style 'flat))
  732. "Displays a summary of the statistics collected. Unless an optional
  733. @var{port} argument is passed, uses the current output port."
  734. (case style
  735. ((flat) (statprof-display/flat port state))
  736. ((anomalies)
  737. (with-output-to-port port
  738. (lambda ()
  739. (statprof-display-anomalies state))))
  740. ((tree) (statprof-display/tree port state))
  741. (else (error "Unknown statprof display style" style))))
  742. (define (call-thunk thunk)
  743. (call-with-values (lambda () (thunk))
  744. (lambda results
  745. (apply values results))))
  746. ;; Prevent inlining of 'call-thunk' so that it can be used to determine
  747. ;; the stack boundaries passed to 'make-stack'.
  748. (set! call-thunk call-thunk)
  749. (define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
  750. (port (current-output-port)) full-stacks?
  751. (display-style 'flat))
  752. "Profile the execution of @var{thunk}, and return its return values.
  753. The stack will be sampled @var{hz} times per second, and the thunk
  754. itself will be called @var{loop} times.
  755. If @var{count-calls?} is true, all procedure calls will be recorded. This
  756. operation is somewhat expensive."
  757. (let ((state (fresh-profiler-state #:count-calls? count-calls?
  758. #:sampling-period
  759. (inexact->exact (round (/ 1e6 hz)))
  760. #:outer-cut
  761. (program-address-range call-thunk))))
  762. (parameterize ((profiler-state state))
  763. (dynamic-wind
  764. (lambda ()
  765. (statprof-start state))
  766. (lambda ()
  767. (let lp ((i loop))
  768. (unless (= i 1)
  769. (call-thunk thunk)
  770. (lp (1- i))))
  771. (call-thunk thunk))
  772. (lambda ()
  773. (statprof-stop state)
  774. (statprof-display port state #:style display-style))))))
  775. (define* (gcprof thunk #:key (loop 1) full-stacks? (port (current-output-port)))
  776. "Do an allocation profile of the execution of @var{thunk}.
  777. The stack will be sampled soon after every garbage collection, yielding
  778. an approximate idea of what is causing allocation in your program.
  779. Since GC does not occur very frequently, you may need to use the
  780. @var{loop} parameter, to cause @var{thunk} to be called @var{loop}
  781. times."
  782. (let ((state (fresh-profiler-state #:outer-cut
  783. (program-address-range call-thunk))))
  784. (parameterize ((profiler-state state))
  785. (define (gc-callback)
  786. (unless (inside-profiler? state)
  787. (set-inside-profiler?! state #t)
  788. (let ((stop-time (get-internal-run-time))
  789. ;; Cut down to gc-callback, and then two more (the
  790. ;; after-gc async and the handle-interrupts trampoline).
  791. ;; See the note in profile-signal-handler also.
  792. (stack (or (make-stack #t gc-callback (outer-cut state) 2)
  793. (pk 'what! (make-stack #t)))))
  794. (sample-stack-procs state stack)
  795. (accumulate-time state stop-time)
  796. (set-last-start-time! state (get-internal-run-time)))
  797. (set-inside-profiler?! state #f)))
  798. (dynamic-wind
  799. (lambda ()
  800. (set-profile-level! state 1)
  801. (set-last-start-time! state (get-internal-run-time))
  802. (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
  803. (add-hook! after-gc-hook gc-callback))
  804. (lambda ()
  805. (let lp ((i loop))
  806. (unless (zero? i)
  807. (call-thunk thunk)
  808. (lp (1- i)))))
  809. (lambda ()
  810. (remove-hook! after-gc-hook gc-callback)
  811. (set-gc-time-taken! state
  812. (- (assq-ref (gc-stats) 'gc-time-taken)
  813. (gc-time-taken state)))
  814. (accumulate-time state (get-internal-run-time))
  815. (set-profile-level! state 0)
  816. (statprof-display port state))))))