statprof.scm 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. ;;;; (statprof) -- a statistical profiler for Guile
  2. ;;;; -*-scheme-*-
  3. ;;;;
  4. ;;;; Copyright (C) 2009, 2010, 2011, 2013-2016 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.
  253. (stack
  254. (or (make-stack #t profile-signal-handler (outer-cut state))
  255. (pk 'what! (make-stack #t)))))
  256. (sample-stack-procs state stack)
  257. (accumulate-time state stop-time)
  258. (set-last-start-time! state (get-internal-run-time))
  259. (reset-sigprof-timer (sampling-period state))))
  260. (set-inside-profiler?! state #f))
  261. profile-signal-handler))
  262. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  263. ;; Count total calls.
  264. (define (count-call frame)
  265. (let ((state (existing-profiler-state)))
  266. (unless (inside-profiler? state)
  267. (let* ((key (frame-instruction-pointer-or-primitive-procedure-name frame))
  268. (handle (hashv-create-handle! (call-counts state) key 0)))
  269. (set-cdr! handle (1+ (cdr handle)))))))
  270. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  271. (define (statprof-active?)
  272. "Returns @code{#t} if @code{statprof-start} has been called more times
  273. than @code{statprof-stop}, @code{#f} otherwise."
  274. (define state (profiler-state))
  275. (and state (positive? (profile-level state))))
  276. ;; Do not call this from statprof internal functions -- user only.
  277. (define* (statprof-start #:optional (state (ensure-profiler-state)))
  278. "Start the profiler.@code{}"
  279. ;; After some head-scratching, I don't *think* I need to mask/unmask
  280. ;; signals here, but if I'm wrong, please let me know.
  281. (set-profile-level! state (+ (profile-level state) 1))
  282. (when (= (profile-level state) 1)
  283. (let ((rpt (remaining-prof-time state)))
  284. (set-remaining-prof-time! state 0)
  285. ;; FIXME: Use per-thread run time.
  286. (set-last-start-time! state (get-internal-run-time))
  287. (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
  288. (let ((prev (sigaction SIGPROF profile-signal-handler)))
  289. (set-prev-sigprof-handler! state (car prev)))
  290. (reset-sigprof-timer (if (zero? rpt) (sampling-period state) rpt))
  291. (when (call-counts state)
  292. (add-hook! (vm-apply-hook) count-call)
  293. (set-vm-trace-level! (1+ (vm-trace-level))))
  294. #t)))
  295. ;; Do not call this from statprof internal functions -- user only.
  296. (define* (statprof-stop #:optional (state (ensure-profiler-state)))
  297. "Stop the profiler.@code{}"
  298. ;; After some head-scratching, I don't *think* I need to mask/unmask
  299. ;; signals here, but if I'm wrong, please let me know.
  300. (set-profile-level! state (- (profile-level state) 1))
  301. (when (zero? (profile-level state))
  302. (when (call-counts state)
  303. (set-vm-trace-level! (1- (vm-trace-level)))
  304. (remove-hook! (vm-apply-hook) count-call))
  305. (set-gc-time-taken! state
  306. (- (assq-ref (gc-stats) 'gc-time-taken)
  307. (gc-time-taken state)))
  308. ;; I believe that we need to do this before getting the time
  309. ;; (unless we want to make things even more complicated).
  310. (set-remaining-prof-time! state (reset-sigprof-timer 0))
  311. (accumulate-time state (get-internal-run-time))
  312. (sigaction SIGPROF (prev-sigprof-handler state))
  313. (set-prev-sigprof-handler! state #f)
  314. (set-last-start-time! state #f)))
  315. (define* (statprof-reset sample-seconds sample-microseconds count-calls?
  316. #:optional full-stacks?)
  317. "Reset the statprof sampler interval to @var{sample-seconds} and
  318. @var{sample-microseconds}. If @var{count-calls?} is true, arrange to
  319. instrument procedure calls as well as collecting statistical profiling
  320. data. (The optional @var{full-stacks?} argument is deprecated; statprof
  321. always collects full stacks.)"
  322. (when (statprof-active?)
  323. (error "Can't reset profiler while profiler is running."))
  324. (profiler-state
  325. (fresh-profiler-state #:count-calls? count-calls?
  326. #:sampling-period (+ (* sample-seconds #e1e6)
  327. sample-microseconds)))
  328. (values))
  329. (define-record-type call-data
  330. (make-call-data name printable source
  331. call-count cum-sample-count self-sample-count)
  332. call-data?
  333. (name call-data-name)
  334. (printable call-data-printable)
  335. (source call-data-source)
  336. (call-count call-data-call-count set-call-data-call-count!)
  337. (cum-sample-count call-data-cum-sample-count set-call-data-cum-sample-count!)
  338. (self-sample-count call-data-self-sample-count set-call-data-self-sample-count!))
  339. (define (source->string source)
  340. (format #f "~a:~a:~a"
  341. (or (source-file source) "<current input>")
  342. (source-line-for-user source)
  343. (source-column source)))
  344. (define (program-debug-info-printable pdi)
  345. (let* ((addr (program-debug-info-addr pdi))
  346. (name (or (and=> (program-debug-info-name pdi) symbol->string)
  347. (string-append "#x" (number->string addr 16))))
  348. (loc (and=> (find-source-for-addr addr) source->string)))
  349. (if loc
  350. (string-append name " at " loc)
  351. name)))
  352. (define (addr->pdi addr cache)
  353. (cond
  354. ((hashv-get-handle cache addr) => cdr)
  355. (else
  356. (let ((data (find-program-debug-info addr)))
  357. (hashv-set! cache addr data)
  358. data))))
  359. (define (addr->printable addr pdi)
  360. (or (and=> (and=> pdi program-debug-info-name) symbol->string)
  361. (string-append "anon #x" (number->string addr 16))))
  362. (define (inc-call-data-cum-sample-count! cd)
  363. (set-call-data-cum-sample-count! cd (1+ (call-data-cum-sample-count cd))))
  364. (define (inc-call-data-self-sample-count! cd)
  365. (set-call-data-self-sample-count! cd (1+ (call-data-self-sample-count cd))))
  366. (define (skip-count-call buffer start len)
  367. ;; If we are counting all procedure calls, count-call might be on the
  368. ;; stack. If it is, skip that part of the stack.
  369. (match (program-address-range count-call)
  370. ((lo . hi)
  371. (let lp ((pos start))
  372. (if (< pos len)
  373. (let ((key (vector-ref buffer pos)))
  374. (cond
  375. ((not key)
  376. ;; End of stack; count-call not on the stack.
  377. start)
  378. ((and (number? key) (<= lo key) (< key hi))
  379. ;; Found count-call.
  380. (1+ pos))
  381. (else
  382. ;; Otherwise keep going.
  383. (lp (1+ pos)))))
  384. start)))))
  385. (define (stack-samples->procedure-data state)
  386. (let ((table (make-hash-table))
  387. (addr-cache (make-hash-table))
  388. (call-counts (call-counts state))
  389. (buffer (buffer state))
  390. (len (buffer-pos state)))
  391. (define (addr->call-data addr)
  392. (let* ((pdi (addr->pdi addr addr-cache))
  393. (entry (if pdi (program-debug-info-addr pdi) addr)))
  394. (or (hashv-ref table entry)
  395. (let ((data (make-call-data (and=> pdi program-debug-info-name)
  396. (addr->printable entry pdi)
  397. (find-source-for-addr entry)
  398. (and call-counts
  399. (hashv-ref call-counts entry))
  400. 0
  401. 0)))
  402. (hashv-set! table entry data)
  403. data))))
  404. (define (callee->call-data callee)
  405. (cond
  406. ((number? callee) (addr->call-data callee))
  407. ((hashv-ref table callee))
  408. (else
  409. (let ((data (make-call-data
  410. (cond ((procedure? callee) (procedure-name callee))
  411. ;; a primitive
  412. ((symbol? callee) callee)
  413. (else #f))
  414. (with-output-to-string (lambda () (write callee)))
  415. #f
  416. (and call-counts (hashv-ref call-counts callee))
  417. 0
  418. 0)))
  419. (hashv-set! table callee data)
  420. data))))
  421. (when call-counts
  422. (hash-for-each (lambda (callee count)
  423. (callee->call-data callee))
  424. call-counts))
  425. (let visit-stacks ((pos 0))
  426. (cond
  427. ((< pos len)
  428. (let ((pos (if call-counts
  429. (skip-count-call buffer pos len)
  430. pos)))
  431. (inc-call-data-self-sample-count!
  432. (callee->call-data (vector-ref buffer pos)))
  433. (let visit-stack ((pos pos))
  434. (cond
  435. ((vector-ref buffer pos)
  436. => (lambda (callee)
  437. (inc-call-data-cum-sample-count! (callee->call-data callee))
  438. (visit-stack (1+ pos))))
  439. (else
  440. (visit-stacks (1+ pos)))))))
  441. (else table)))))
  442. (define (stack-samples->callee-lists state)
  443. (let ((buffer (buffer state))
  444. (len (buffer-pos state)))
  445. (let visit-stacks ((pos 0) (out '()))
  446. (cond
  447. ((< pos len)
  448. (let visit-stack ((pos (if (call-counts state)
  449. (skip-count-call buffer pos len)
  450. pos))
  451. (stack '()))
  452. (cond
  453. ((vector-ref buffer pos)
  454. => (lambda (callee)
  455. (visit-stack (1+ pos) (cons callee stack))))
  456. (else
  457. (visit-stacks (1+ pos) (cons (reverse stack) out))))))
  458. (else (reverse out))))))
  459. (define* (statprof-fold-call-data proc init #:optional
  460. (state (existing-profiler-state)))
  461. "Fold @var{proc} over the call-data accumulated by statprof. Cannot be
  462. called while statprof is active. @var{proc} should take two arguments,
  463. @code{(@var{call-data} @var{prior-result})}.
  464. Note that a given proc-name may appear multiple times, but if it does,
  465. it represents different functions with the same name."
  466. (when (statprof-active?)
  467. (error "Can't call statprof-fold-call-data while profiler is running."))
  468. (hash-fold
  469. (lambda (key value prior-result)
  470. (proc value prior-result))
  471. init
  472. (stack-samples->procedure-data state)))
  473. (define* (statprof-proc-call-data proc #:optional
  474. (state (existing-profiler-state)))
  475. "Returns the call-data associated with @var{proc}, or @code{#f} if
  476. none is available."
  477. (when (statprof-active?)
  478. (error "Can't call statprof-proc-call-data while profiler is running."))
  479. (unless (program? proc)
  480. (error "statprof-call-data only works for VM programs"))
  481. (let* ((code (program-code proc))
  482. (key (if (primitive-code? code)
  483. (procedure-name proc)
  484. code)))
  485. (hashv-ref (stack-samples->procedure-data state) key)))
  486. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  487. ;; Stats
  488. (define-record-type stats
  489. (make-stats proc-name proc-source
  490. %-time-in-proc cum-secs-in-proc self-secs-in-proc
  491. calls)
  492. stats?
  493. (proc-name statprof-stats-proc-name)
  494. (proc-source statprof-stats-proc-source)
  495. (%-time-in-proc statprof-stats-%-time-in-proc)
  496. (cum-secs-in-proc statprof-stats-cum-secs-in-proc)
  497. (self-secs-in-proc statprof-stats-self-secs-in-proc)
  498. (calls statprof-stats-calls))
  499. (define (statprof-stats-self-secs-per-call stats)
  500. (let ((calls (statprof-stats-calls stats)))
  501. (and calls
  502. (/ (statprof-stats-self-secs-in-proc stats)
  503. calls))))
  504. (define (statprof-stats-cum-secs-per-call stats)
  505. (let ((calls (statprof-stats-calls stats)))
  506. (and calls
  507. (/ (statprof-stats-cum-secs-in-proc stats)
  508. ;; `calls' might be 0 if we entered statprof during the
  509. ;; dynamic extent of the call.
  510. (max calls 1)))))
  511. (define (statprof-call-data->stats call-data)
  512. "Returns an object of type @code{statprof-stats}."
  513. (define state (existing-profiler-state))
  514. (let* ((proc-name (call-data-name call-data))
  515. (proc-source (and=> (call-data-source call-data) source->string))
  516. (self-samples (call-data-self-sample-count call-data))
  517. (cum-samples (call-data-cum-sample-count call-data))
  518. (all-samples (statprof-sample-count state))
  519. (secs-per-sample (/ (statprof-accumulated-time state)
  520. (statprof-sample-count state)))
  521. (num-calls (and (call-counts state)
  522. (statprof-call-data-calls call-data))))
  523. (make-stats (or proc-name
  524. ;; If there is no name and no source, fall back to
  525. ;; printable.
  526. (and (not proc-source) (call-data-printable call-data)))
  527. proc-source
  528. (* (/ self-samples all-samples) 100.0)
  529. (* cum-samples secs-per-sample 1.0)
  530. (* self-samples secs-per-sample 1.0)
  531. num-calls)))
  532. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  533. (define (stats-sorter x y)
  534. (let ((diff (- (statprof-stats-self-secs-in-proc x)
  535. (statprof-stats-self-secs-in-proc y))))
  536. (positive?
  537. (if (= diff 0)
  538. (- (statprof-stats-cum-secs-in-proc x)
  539. (statprof-stats-cum-secs-in-proc y))
  540. diff))))
  541. (define* (statprof-display/flat port state)
  542. "Displays a gprof-like summary of the statistics collected. Unless an
  543. optional @var{port} argument is passed, uses the current output port."
  544. (cond
  545. ((zero? (statprof-sample-count state))
  546. (format port "No samples recorded.\n"))
  547. (else
  548. (let* ((stats-list (statprof-fold-call-data
  549. (lambda (data prior-value)
  550. (cons (statprof-call-data->stats data)
  551. prior-value))
  552. '()
  553. state))
  554. (sorted-stats (sort stats-list stats-sorter)))
  555. (define (display-stats-line stats)
  556. (format port "~6,2f ~9,2f ~9,2f"
  557. (statprof-stats-%-time-in-proc stats)
  558. (statprof-stats-cum-secs-in-proc stats)
  559. (statprof-stats-self-secs-in-proc stats))
  560. (if (call-counts state)
  561. (if (statprof-stats-calls stats)
  562. (format port " ~7d "
  563. (statprof-stats-calls stats))
  564. (format port " "))
  565. (display " " port))
  566. (let ((source (statprof-stats-proc-source stats))
  567. (name (statprof-stats-proc-name stats)))
  568. (when source
  569. (display source port)
  570. (when name
  571. (display ":" port)))
  572. (when name
  573. (display name port))
  574. (newline port)))
  575. (if (call-counts state)
  576. (begin
  577. (format port "~5a ~10a ~7a ~8a\n"
  578. "% " "cumulative" "self" "")
  579. (format port "~5a ~9a ~8a ~7a ~a\n"
  580. "time" "seconds" "seconds" "calls" "procedure"))
  581. (begin
  582. (format port "~5a ~10a ~7a ~8a\n"
  583. "%" "cumulative" "self" "")
  584. (format port "~5a ~10a ~7a ~a\n"
  585. "time" "seconds" "seconds" "procedure")))
  586. (for-each display-stats-line sorted-stats)
  587. (display "---\n" port)
  588. (format #t "Sample count: ~A\n" (statprof-sample-count state))
  589. (format #t "Total time: ~A seconds (~A seconds in GC)\n"
  590. (statprof-accumulated-time state)
  591. (/ (gc-time-taken state)
  592. 1.0 internal-time-units-per-second))))))
  593. (define* (statprof-display-anomalies #:optional (state
  594. (existing-profiler-state)))
  595. "A sanity check that attempts to detect anomalies in statprof's
  596. statistics.@code{}"
  597. (statprof-fold-call-data
  598. (lambda (data prior-value)
  599. (when (and (call-counts state)
  600. (zero? (call-data-call-count data))
  601. (positive? (call-data-cum-sample-count data)))
  602. (format #t
  603. "==[~A ~A ~A]\n"
  604. (call-data-name data)
  605. (call-data-call-count data)
  606. (call-data-cum-sample-count data))))
  607. #f
  608. state)
  609. (format #t "Total time: ~A\n" (statprof-accumulated-time state))
  610. (format #t "Sample count: ~A\n" (statprof-sample-count state)))
  611. (define (statprof-display-anomolies)
  612. (issue-deprecation-warning "statprof-display-anomolies is a misspelling. "
  613. "Use statprof-display-anomalies instead.")
  614. (statprof-display-anomalies))
  615. (define* (statprof-accumulated-time #:optional (state
  616. (existing-profiler-state)))
  617. "Returns the time accumulated during the last statprof run.@code{}"
  618. (/ (accumulated-time state) 1.0 internal-time-units-per-second))
  619. (define* (statprof-sample-count #:optional (state (existing-profiler-state)))
  620. "Returns the number of samples taken during the last statprof run.@code{}"
  621. (sample-count state))
  622. (define statprof-call-data-name call-data-name)
  623. (define statprof-call-data-calls call-data-call-count)
  624. (define statprof-call-data-cum-samples call-data-cum-sample-count)
  625. (define statprof-call-data-self-samples call-data-self-sample-count)
  626. (define* (statprof-fetch-stacks #:optional (state (existing-profiler-state)))
  627. "Returns a list of stacks, as they were captured since the last call
  628. to @code{statprof-reset}."
  629. (stack-samples->callee-lists state))
  630. ;; tree ::= (car n . tree*)
  631. (define (lists->trees lists equal?)
  632. (let lp ((in lists) (n-terminal 0) (tails '()))
  633. (cond
  634. ((null? in)
  635. (let ((trees (map (lambda (tail)
  636. (cons (car tail)
  637. (lists->trees (cdr tail) equal?)))
  638. tails)))
  639. (cons (apply + n-terminal (map cadr trees))
  640. (sort trees
  641. (lambda (a b) (> (cadr a) (cadr b)))))))
  642. ((null? (car in))
  643. (lp (cdr in) (1+ n-terminal) tails))
  644. ((find (lambda (x) (equal? (car x) (caar in)))
  645. tails)
  646. => (lambda (tail)
  647. (lp (cdr in)
  648. n-terminal
  649. (assq-set! tails
  650. (car tail)
  651. (cons (cdar in) (cdr tail))))))
  652. (else
  653. (lp (cdr in)
  654. n-terminal
  655. (acons (caar in) (list (cdar in)) tails))))))
  656. (define (collect-cycles items)
  657. (define (find-cycle item stack)
  658. (match (vhash-assoc item stack)
  659. (#f #f)
  660. ((_ . pos)
  661. (let ((size (- (vlist-length stack) pos)))
  662. (and (<= (1- (* size 2)) (vlist-length stack))
  663. (let lp ((i 0))
  664. (if (= i (1- size))
  665. size
  666. (and (equal? (car (vlist-ref stack i))
  667. (car (vlist-ref stack (+ i size))))
  668. (lp (1+ i))))))))))
  669. (define (collect-cycle stack size)
  670. (vlist-fold-right (lambda (pair cycle)
  671. (cons (car pair) cycle))
  672. '()
  673. (vlist-take stack size)))
  674. (define (detect-cycle items stack)
  675. (match items
  676. (() stack)
  677. ((item . items)
  678. (let* ((cycle-size (find-cycle item stack)))
  679. (if cycle-size
  680. (chomp-cycles (collect-cycle stack cycle-size)
  681. items
  682. (vlist-drop stack (1- (* cycle-size 2))))
  683. (chomp-cycles (list item) items stack))))))
  684. (define (skip-cycles cycle items)
  685. (let lp ((a cycle) (b items))
  686. (match a
  687. (() (skip-cycles cycle b))
  688. ((a . a*)
  689. (match b
  690. (() items)
  691. ((b . b*)
  692. (if (equal? a b)
  693. (lp a* b*)
  694. items)))))))
  695. (define (chomp-cycles cycle items stack)
  696. (detect-cycle (skip-cycles cycle items)
  697. (vhash-cons (match cycle
  698. ((item) item)
  699. (cycle cycle))
  700. (vlist-length stack)
  701. stack)))
  702. (vlist-fold
  703. (lambda (pair out)
  704. (cons (car pair) out))
  705. '()
  706. (detect-cycle items vlist-null)))
  707. (define* (statprof-fetch-call-tree #:optional (state (existing-profiler-state))
  708. #:key precise?)
  709. "Return a call tree for the previous statprof run.
  710. The return value is a list of nodes, each of which is of the type:
  711. @code
  712. node ::= (@var{proc} @var{count} . @var{nodes})
  713. @end code"
  714. (define-syntax-rule (define-memoized (fn arg) body)
  715. (define fn
  716. (let ((table (make-hash-table)))
  717. (lambda (arg)
  718. (cond
  719. ((hash-get-handle table arg) => cdr)
  720. (else
  721. (let ((res body))
  722. (hash-set! table arg res)
  723. res)))))))
  724. (define-memoized (callee->printable callee)
  725. (cond
  726. ((number? callee)
  727. (let* ((pdi (find-program-debug-info callee))
  728. (name (or (and=> (and pdi (program-debug-info-name pdi))
  729. symbol->string)
  730. (string-append "#x" (number->string callee 16))))
  731. (loc (and=> (find-source-for-addr
  732. (or (and (not precise?)
  733. (and=> pdi program-debug-info-addr))
  734. callee))
  735. source->string)))
  736. (if loc
  737. (string-append name " at " loc)
  738. name)))
  739. (else
  740. (with-output-to-string (lambda () (write callee))))))
  741. (define (munge-stack stack)
  742. ;; We collect the sample in newest-to-oldest
  743. ;; order. Change to have the oldest first.
  744. (let ((stack (reverse stack)))
  745. (define (cycle->printable item)
  746. (if (string? item)
  747. item
  748. (string-join (map cycle->printable item) ", ")))
  749. (map cycle->printable (collect-cycles (map callee->printable stack)))))
  750. (let ((stacks (map munge-stack (stack-samples->callee-lists state))))
  751. (cons #t (lists->trees stacks equal?))))
  752. (define (statprof-display/tree port state)
  753. (match (statprof-fetch-call-tree state)
  754. ((#t total-count . trees)
  755. (define (print-tree tree indent)
  756. (define (print-subtree tree) (print-tree tree (+ indent 2)))
  757. (match tree
  758. ((callee count . trees)
  759. (format port "~vt~,1f% ~a\n" indent (* 100. (/ count total-count))
  760. callee)
  761. (for-each print-subtree trees))))
  762. (for-each (lambda (tree) (print-tree tree 0)) trees)))
  763. (display "---\n" port)
  764. (format port "Sample count: ~A\n" (statprof-sample-count state))
  765. (format port "Total time: ~A seconds (~A seconds in GC)\n"
  766. (statprof-accumulated-time state)
  767. (/ (gc-time-taken state)
  768. 1.0 internal-time-units-per-second)))
  769. (define* (statprof-display #:optional (port (current-output-port))
  770. (state (existing-profiler-state))
  771. #:key (style 'flat))
  772. "Displays a summary of the statistics collected. Unless an optional
  773. @var{port} argument is passed, uses the current output port."
  774. (case style
  775. ((flat) (statprof-display/flat port state))
  776. ((anomalies)
  777. (with-output-to-port port
  778. (lambda ()
  779. (statprof-display-anomalies state))))
  780. ((tree) (statprof-display/tree port state))
  781. (else (error "Unknown statprof display style" style))))
  782. (define (call-thunk thunk)
  783. (call-with-values (lambda () (thunk))
  784. (lambda results
  785. (apply values results))))
  786. (define* (statprof thunk #:key (loop 1) (hz 100) (count-calls? #f)
  787. (port (current-output-port)) full-stacks?
  788. (display-style 'flat))
  789. "Profile the execution of @var{thunk}, and return its return values.
  790. The stack will be sampled @var{hz} times per second, and the thunk
  791. itself will be called @var{loop} times.
  792. If @var{count-calls?} is true, all procedure calls will be recorded. This
  793. operation is somewhat expensive."
  794. (let ((state (fresh-profiler-state #:count-calls? count-calls?
  795. #:sampling-period
  796. (inexact->exact (round (/ 1e6 hz)))
  797. #:outer-cut
  798. (program-address-range call-thunk))))
  799. (parameterize ((profiler-state state))
  800. (dynamic-wind
  801. (lambda ()
  802. (statprof-start state))
  803. (lambda ()
  804. (let lp ((i loop))
  805. (unless (= i 1)
  806. (call-thunk thunk)
  807. (lp (1- i))))
  808. (call-thunk thunk))
  809. (lambda ()
  810. (statprof-stop state)
  811. (statprof-display port state #:style display-style))))))
  812. (begin-deprecated
  813. (define-macro (with-statprof . args)
  814. "Profile the expressions in the body, and return the body's return values.
  815. Keyword arguments:
  816. @table @code
  817. @item #:loop
  818. Execute the body @var{loop} number of times, or @code{#f} for no looping
  819. default: @code{#f}
  820. @item #:hz
  821. Sampling rate
  822. default: @code{20}
  823. @item #:count-calls?
  824. Whether to instrument each function call (expensive)
  825. default: @code{#f}
  826. @end table"
  827. (define (kw-arg-ref kw args def)
  828. (cond
  829. ((null? args) (error "Invalid macro body"))
  830. ((keyword? (car args))
  831. (if (eq? (car args) kw)
  832. (cadr args)
  833. (kw-arg-ref kw (cddr args) def)))
  834. ((eq? kw #f def) ;; asking for the body
  835. args)
  836. (else def))) ;; kw not found
  837. (issue-deprecation-warning
  838. "`with-statprof' is deprecated. Use `statprof' instead.")
  839. `((@ (statprof) statprof)
  840. (lambda () ,@(kw-arg-ref #f args #f))
  841. #:loop ,(kw-arg-ref #:loop args 1)
  842. #:hz ,(kw-arg-ref #:hz args 100)
  843. #:count-calls? ,(kw-arg-ref #:count-calls? args #f)))
  844. (export with-statprof))
  845. (define* (gcprof thunk #:key (loop 1) full-stacks? (port (current-output-port)))
  846. "Do an allocation profile of the execution of @var{thunk}.
  847. The stack will be sampled soon after every garbage collection, yielding
  848. an approximate idea of what is causing allocation in your program.
  849. Since GC does not occur very frequently, you may need to use the
  850. @var{loop} parameter, to cause @var{thunk} to be called @var{loop}
  851. times."
  852. (let ((state (fresh-profiler-state #:outer-cut
  853. (program-address-range call-thunk))))
  854. (parameterize ((profiler-state state))
  855. (define (gc-callback)
  856. (unless (inside-profiler? state)
  857. (set-inside-profiler?! state #t)
  858. (let ((stop-time (get-internal-run-time))
  859. ;; Cut down to gc-callback, and then one before (the
  860. ;; after-gc async). See the note in profile-signal-handler
  861. ;; also.
  862. (stack (or (make-stack #t gc-callback (outer-cut state) 1)
  863. (pk 'what! (make-stack #t)))))
  864. (sample-stack-procs state stack)
  865. (accumulate-time state stop-time)
  866. (set-last-start-time! state (get-internal-run-time)))
  867. (set-inside-profiler?! state #f)))
  868. (dynamic-wind
  869. (lambda ()
  870. (set-profile-level! state 1)
  871. (set-last-start-time! state (get-internal-run-time))
  872. (set-gc-time-taken! state (assq-ref (gc-stats) 'gc-time-taken))
  873. (add-hook! after-gc-hook gc-callback))
  874. (lambda ()
  875. (let lp ((i loop))
  876. (unless (zero? i)
  877. (call-thunk thunk)
  878. (lp (1- i)))))
  879. (lambda ()
  880. (remove-hook! after-gc-hook gc-callback)
  881. (set-gc-time-taken! state
  882. (- (assq-ref (gc-stats) 'gc-time-taken)
  883. (gc-time-taken state)))
  884. (accumulate-time state (get-internal-run-time))
  885. (set-profile-level! state 0)
  886. (statprof-display port state))))))