statprof.scm 38 KB

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