statprof.scm 38 KB

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