profiler.el 25.8 KB
Newer Older
1 2
;;; profiler.el --- UI and helper functions for Emacs's native profiler -*- lexical-binding: t -*-

3
;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

;; Author: Tomohiro Matsuyama <tomo@cx4a.org>
;; Keywords: lisp

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

Glenn Morris's avatar
Comment  
Glenn Morris committed
23
;; See Info node `(elisp)Profiling'.
24 25 26

;;; Code:

27
(require 'cl-lib)
28 29 30 31

(defgroup profiler nil
  "Emacs profiler."
  :group 'lisp
Glenn Morris's avatar
Glenn Morris committed
32
  :version "24.3"
33 34
  :prefix "profiler-")

35 36
(defconst profiler-version "24.3")

37 38
(defcustom profiler-sampling-interval 1000000
  "Default sampling interval in nanoseconds."
39 40 41
  :type 'integer
  :group 'profiler)

42

43 44 45
;;; Utilities

(defun profiler-ensure-string (object)
46 47 48 49 50 51 52 53
  (cond ((stringp object)
	 object)
	((symbolp object)
	 (symbol-name object))
	((numberp object)
	 (number-to-string object))
	(t
	 (format "%s" object))))
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
(defun profiler-format-percent (number divisor)
  (concat (number-to-string (/ (* number 100) divisor)) "%"))

(defun profiler-format-number (number)
  "Format NUMBER in human readable string."
  (if (and (integerp number) (> number 0))
      (cl-loop with i = (% (1+ (floor (log10 number))) 3)
	       for c in (append (number-to-string number) nil)
	       if (= i 0)
	       collect ?, into s
	       and do (setq i 3)
	       collect c into s
	       do (cl-decf i)
	       finally return
	       (apply 'string (if (eq (car s) ?,) (cdr s) s)))
    (profiler-ensure-string number)))

72
(defun profiler-format (fmt &rest args)
73 74
  (cl-loop for (width align subfmt) in fmt
	   for arg in args
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
75 76 77 78 79 80 81 82 83 84
	   for str = (cond
		      ((consp subfmt)
		       (apply 'profiler-format subfmt arg))
		      ((stringp subfmt)
		       (format subfmt arg))
		      ((and (symbolp subfmt)
			    (fboundp subfmt))
		       (funcall subfmt arg))
		      (t
		       (profiler-ensure-string arg)))
85 86 87 88 89 90 91 92 93 94 95
	   for len = (length str)
	   if (< width len)
	   collect (substring str 0 width) into frags
	   else
	   collect
	   (let ((padding (make-string (- width len) ?\s)))
	     (cl-ecase align
	       (left (concat str padding))
	       (right (concat padding str))))
	   into frags
	   finally return (apply #'concat frags)))
96

Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
97

98 99
;;; Entries

100
(defun profiler-format-entry (entry)
101 102
  "Format ENTRY in human readable string.  ENTRY would be a
function name of a function itself."
103 104 105
  (cond ((memq (car-safe entry) '(closure lambda))
	 (format "#<lambda 0x%x>" (sxhash entry)))
	((byte-code-function-p entry)
106
	 (format "#<compiled 0x%x>" (sxhash entry)))
107 108
	((or (subrp entry) (symbolp entry) (stringp entry))
	 (format "%s" entry))
109 110
	(t
	 (format "#<unknown 0x%x>" (sxhash entry)))))
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
111

112 113 114 115 116 117 118 119 120 121 122 123 124
(defun profiler-fixup-entry (entry)
  (if (symbolp entry)
      entry
    (profiler-format-entry entry)))


;;; Backtraces

(defun profiler-fixup-backtrace (backtrace)
  (apply 'vector (mapcar 'profiler-fixup-entry backtrace)))


;;; Logs
125

126 127 128 129 130
;; The C code returns the log in the form of a hash-table where the keys are
;; vectors (of size profiler-max-stack-depth, holding truncated
;; backtraces, where the first element is the top of the stack) and
;; the values are integers (which count how many times this backtrace
;; has been seen, multiplied by a "weight factor" which is either the
131 132 133 134
;; sampling-interval or the memory being allocated).

(defun profiler-compare-logs (log1 log2)
  "Compare LOG1 with LOG2 and return diff."
135 136 137 138 139
  (let ((newlog (make-hash-table :test 'equal)))
    ;; Make a copy of `log1' into `newlog'.
    (maphash (lambda (backtrace count) (puthash backtrace count newlog))
             log1)
    (maphash (lambda (backtrace count)
140 141
               (puthash backtrace (- (gethash backtrace log1 0) count)
                        newlog))
142 143
             log2)
    newlog))
144

145
(defun profiler-fixup-log (log)
146 147
  (let ((newlog (make-hash-table :test 'equal)))
    (maphash (lambda (backtrace count)
148
               (puthash (profiler-fixup-backtrace backtrace)
149 150 151
                        count newlog))
             log)
    newlog))
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

;;; Profiles

(cl-defstruct (profiler-profile (:type vector)
                                (:constructor profiler-make-profile))
  (tag 'profiler-profile)
  (version profiler-version)
  ;; - `type' has a value indicating the kind of profile (`memory' or `cpu').
  ;; - `log' indicates the profile log.
  ;; - `timestamp' has a value giving the time when the profile was obtained.
  ;; - `diff-p' indicates if this profile represents a diff between two profiles.
  type log timestamp diff-p)

(defun profiler-compare-profiles (profile1 profile2)
  "Compare PROFILE1 with PROFILE2 and return diff."
  (unless (eq (profiler-profile-type profile1)
	      (profiler-profile-type profile2))
    (error "Can't compare different type of profiles"))
  (profiler-make-profile
   :type (profiler-profile-type profile1)
   :timestamp (current-time)
   :diff-p t
   :log (profiler-compare-logs
         (profiler-profile-log profile1)
         (profiler-profile-log profile2))))

(defun profiler-fixup-profile (profile)
  "Fixup PROFILE so that the profile could be serialized into file."
  (profiler-make-profile
   :type (profiler-profile-type profile)
   :timestamp (profiler-profile-timestamp profile)
   :diff-p (profiler-profile-diff-p profile)
   :log (profiler-fixup-log (profiler-profile-log profile))))

(defun profiler-write-profile (profile filename &optional confirm)
  "Write PROFILE into file FILENAME."
189 190
  (with-temp-buffer
    (let (print-level print-length)
191 192
      (print (profiler-fixup-profile profile)
             (current-buffer)))
193
    (write-file filename confirm)))
194

195 196 197
(defun profiler-read-profile (filename)
  "Read profile from file FILENAME."
  ;; FIXME: tag and version check
198 199 200 201
  (with-temp-buffer
    (insert-file-contents filename)
    (goto-char (point-min))
    (read (current-buffer))))
202

Glenn Morris's avatar
Glenn Morris committed
203 204 205 206 207 208 209 210 211
(defun profiler-running-p (&optional mode)
  "Return non-nil if the profiler is running.
Optional argument MODE means only check for the specified mode (cpu or mem)."
  (cond ((eq mode 'cpu) (and (fboundp 'profiler-cpu-running-p)
                             (profiler-cpu-running-p)))
        ((eq mode 'mem) (profiler-memory-running-p))
        (t (or (profiler-running-p 'cpu)
               (profiler-running-p 'mem)))))

212 213
(defun profiler-cpu-profile ()
  "Return CPU profile."
Glenn Morris's avatar
Glenn Morris committed
214
  (when (profiler-running-p 'cpu)
215 216 217 218 219 220 221 222 223 224 225 226 227
    (profiler-make-profile
     :type 'cpu
     :timestamp (current-time)
     :log (profiler-cpu-log))))

(defun profiler-memory-profile ()
  "Return memory profile."
  (when (profiler-memory-running-p)
    (profiler-make-profile
     :type 'memory
     :timestamp (current-time)
     :log (profiler-memory-log))))

228

229
;;; Calltrees
230

231
(cl-defstruct (profiler-calltree (:constructor profiler-make-calltree))
232
  entry
233
  (count 0) (count-percent "")
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  parent children)

(defun profiler-calltree-leaf-p (tree)
  (null (profiler-calltree-children tree)))

(defun profiler-calltree-count< (a b)
  (cond ((eq (profiler-calltree-entry a) t) t)
	((eq (profiler-calltree-entry b) t) nil)
	(t (< (profiler-calltree-count a)
	      (profiler-calltree-count b)))))

(defun profiler-calltree-count> (a b)
  (not (profiler-calltree-count< a b)))

(defun profiler-calltree-depth (tree)
  (let ((parent (profiler-calltree-parent tree)))
    (if (null parent)
	0
      (1+ (profiler-calltree-depth parent)))))

(defun profiler-calltree-find (tree entry)
255 256
  "Return a child tree of ENTRY under TREE."
  (let (result (children (profiler-calltree-children tree)))
257
    ;; FIXME: Use `assoc'.
258 259
    (while (and children (null result))
      (let ((child (car children)))
260
	(when (equal (profiler-calltree-entry child) entry)
261 262 263 264
	  (setq result child))
	(setq children (cdr children))))
    result))

265 266
(defun profiler-calltree-walk (calltree function)
  (funcall function calltree)
267
  (dolist (child (profiler-calltree-children calltree))
268
    (profiler-calltree-walk child function)))
269 270

(defun profiler-calltree-build-1 (tree log &optional reverse)
Stefan Monnier's avatar
Stefan Monnier committed
271 272 273 274
  ;; FIXME: Do a better job of reconstructing a complete call-tree
  ;; when the backtraces have been truncated.  Ideally, we should be
  ;; able to reduce profiler-max-stack-depth to 3 or 4 and still
  ;; get a meaningful call-tree.
275 276
  (maphash
   (lambda (backtrace count)
277 278 279 280 281 282 283 284 285 286 287 288
     (let ((node tree)
           (max (length backtrace)))
       (dotimes (i max)
         (let ((entry (aref backtrace (if reverse i (- max i 1)))))
           (when entry
             (let ((child (profiler-calltree-find node entry)))
               (unless child
                 (setq child (profiler-make-calltree
                              :entry entry :parent node))
                 (push child (profiler-calltree-children node)))
               (cl-incf (profiler-calltree-count child) count)
               (setq node child)))))))
289
   log))
290

291
(defun profiler-calltree-compute-percentages (tree)
292
  (let ((total-count 0))
293
    ;; FIXME: the memory profiler's total wraps around all too easily!
294
    (dolist (child (profiler-calltree-children tree))
295 296 297 298 299 300 301
      (cl-incf total-count (profiler-calltree-count child)))
    (unless (zerop total-count)
      (profiler-calltree-walk
       tree (lambda (node)
              (setf (profiler-calltree-count-percent node)
                    (profiler-format-percent (profiler-calltree-count node)
                                             total-count)))))))
302

303
(cl-defun profiler-calltree-build (log &key reverse)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  (let ((tree (profiler-make-calltree)))
    (profiler-calltree-build-1 tree log reverse)
    (profiler-calltree-compute-percentages tree)
    tree))

(defun profiler-calltree-sort (tree predicate)
  (let ((children (profiler-calltree-children tree)))
    (setf (profiler-calltree-children tree) (sort children predicate))
    (dolist (child (profiler-calltree-children tree))
      (profiler-calltree-sort child predicate))))


;;; Report rendering

(defcustom profiler-report-closed-mark "+"
  "An indicator of closed calltrees."
  :type 'string
  :group 'profiler)

(defcustom profiler-report-open-mark "-"
  "An indicator of open calltrees."
  :type 'string
  :group 'profiler)

(defcustom profiler-report-leaf-mark " "
  "An indicator of calltree leaves."
  :type 'string
  :group 'profiler)

333
(defvar profiler-report-cpu-line-format
334 335
  '((50 left)
    (24 right ((19 right)
336 337 338
	       (5 right)))))

(defvar profiler-report-memory-line-format
Tomohiro Matsuyama's avatar
Tomohiro Matsuyama committed
339
  '((55 left)
340
    (19 right ((14 right profiler-format-number)
341 342
	       (5 right)))))

343 344
(defvar-local profiler-report-profile nil
  "The current profile.")
345

346
(defvar-local profiler-report-reversed nil
347 348 349
  "True if calltree is rendered in bottom-up.  Do not touch this
variable directly.")

350
(defvar-local profiler-report-order nil
351 352
  "The value can be `ascending' or `descending'.  Do not touch
this variable directly.")
353 354

(defun profiler-report-make-entry-part (entry)
355 356 357 358 359 360 361 362
  (let ((string (cond
		 ((eq entry t)
		  "Others")
		 ((and (symbolp entry)
		       (fboundp entry))
		  (propertize (symbol-name entry)
			      'face 'link
			      'mouse-face 'highlight
363 364 365
			      'help-echo "\
mouse-2: jump to definition\n\
RET: expand or collapse"))
366
		 (t
367
		  (profiler-format-entry entry)))))
368
    (propertize string 'profiler-entry entry)))
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

(defun profiler-report-make-name-part (tree)
  (let* ((entry (profiler-calltree-entry tree))
	 (depth (profiler-calltree-depth tree))
	 (indent (make-string (* (1- depth) 2) ?\s))
	 (mark (if (profiler-calltree-leaf-p tree)
		   profiler-report-leaf-mark
		 profiler-report-closed-mark))
	 (entry (profiler-report-make-entry-part entry)))
    (format "%s%s %s" indent mark entry)))

(defun profiler-report-header-line-format (fmt &rest args)
  (let* ((header (apply 'profiler-format fmt args))
	 (escaped (replace-regexp-in-string "%" "%%" header)))
    (concat " " escaped)))

(defun profiler-report-line-format (tree)
386
  (let ((diff-p (profiler-profile-diff-p profiler-report-profile))
387 388 389
	(name-part (profiler-report-make-name-part tree))
	(count (profiler-calltree-count tree))
	(count-percent (profiler-calltree-count-percent tree)))
390 391
    (profiler-format (cl-ecase (profiler-profile-type profiler-report-profile)
		       (cpu profiler-report-cpu-line-format)
392 393 394 395 396 397 398 399
		       (memory profiler-report-memory-line-format))
		     name-part
		     (if diff-p
			 (list (if (> count 0)
				   (format "+%s" count)
				 count)
			       "")
		       (list count count-percent)))))
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

(defun profiler-report-insert-calltree (tree)
  (let ((line (profiler-report-line-format tree)))
    (insert (propertize (concat line "\n") 'calltree tree))))

(defun profiler-report-insert-calltree-children (tree)
  (mapc 'profiler-report-insert-calltree
	(profiler-calltree-children tree)))


;;; Report mode

(defvar profiler-report-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "n"	    'profiler-report-next-entry)
    (define-key map "p"	    'profiler-report-previous-entry)
416 417 418 419
    ;; I find it annoying more than helpful to not be able to navigate
    ;; normally with the cursor keys.  --Stef
    ;; (define-key map [down]  'profiler-report-next-entry)
    ;; (define-key map [up]    'profiler-report-previous-entry)
420 421 422 423 424 425 426 427 428 429 430
    (define-key map "\r"    'profiler-report-toggle-entry)
    (define-key map "\t"    'profiler-report-toggle-entry)
    (define-key map "i"     'profiler-report-toggle-entry)
    (define-key map "f"     'profiler-report-find-entry)
    (define-key map "j"     'profiler-report-find-entry)
    (define-key map [mouse-2] 'profiler-report-find-entry)
    (define-key map "d"	    'profiler-report-describe-entry)
    (define-key map "C"	    'profiler-report-render-calltree)
    (define-key map "B"	    'profiler-report-render-reversed-calltree)
    (define-key map "A"	    'profiler-report-ascending-sort)
    (define-key map "D"	    'profiler-report-descending-sort)
431 432
    (define-key map "="	    'profiler-report-compare-profile)
    (define-key map (kbd "C-x C-w") 'profiler-report-write-profile)
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    (easy-menu-define  profiler-report-menu map "Menu for Profiler Report mode."
      '("Profiler"
        ["Next Entry" profiler-report-next-entry :active t
         :help "Move to next entry"]
        ["Previous Entry" profiler-report-previous-entry :active t
         :help "Move to previous entry"]
        "--"
        ["Toggle Entry" profiler-report-toggle-entry
         :active (profiler-report-calltree-at-point)
         :help "Expand or collapse the current entry"]
        ["Find Entry" profiler-report-find-entry
         ;; FIXME should deactivate if not on a known function.
         :active (profiler-report-calltree-at-point)
         :help "Find the definition of the current entry"]
        ["Describe Entry" profiler-report-describe-entry
         :active (profiler-report-calltree-at-point)
         :help "Show the documentation of the current entry"]
        "--"
        ["Show Calltree" profiler-report-render-calltree
         :active profiler-report-reversed
         :help "Show calltree view"]
        ["Show Reversed Calltree" profiler-report-render-reversed-calltree
         :active (not profiler-report-reversed)
         :help "Show reversed calltree view"]
        ["Sort Ascending" profiler-report-ascending-sort
         :active (not (eq profiler-report-order 'ascending))
         :help "Sort calltree view in ascending order"]
        ["Sort Descending" profiler-report-descending-sort
         :active (not (eq profiler-report-order 'descending))
         :help "Sort calltree view in descending order"]
        "--"
        ["Compare Profile..." profiler-report-compare-profile :active t
         :help "Compare current profile with another"]
        ["Write Profile..." profiler-report-write-profile :active t
Glenn Morris's avatar
Glenn Morris committed
467 468 469 470 471 472
         :help "Write current profile to a file"]
        "--"
        ["Stop Profiler" profiler-stop :active (profiler-running-p)
         :help "Stop profiling"]
        ["New Report" profiler-report :active (profiler-running-p)
         :help "Make a new report"]))
473 474
      map)
  "Keymap for `profiler-report-mode'.")
475

476
(defun profiler-report-make-buffer-name (profile)
477
  (format "*%s-Profiler-Report %s*"
478 479
          (cl-ecase (profiler-profile-type profile) (cpu 'CPU) (memory 'Memory))
          (format-time-string "%Y-%m-%d %T" (profiler-profile-timestamp profile))))
480

481 482 483
(defun profiler-report-setup-buffer-1 (profile)
  "Make a buffer for PROFILE and return it."
  (let* ((buf-name (profiler-report-make-buffer-name profile))
484 485 486
	 (buffer (get-buffer-create buf-name)))
    (with-current-buffer buffer
      (profiler-report-mode)
487
      (setq profiler-report-profile profile
488 489 490 491
	    profiler-report-reversed nil
	    profiler-report-order 'descending))
    buffer))

492 493 494 495 496 497 498 499
(defun profiler-report-setup-buffer (profile)
  "Make a buffer for PROFILE with rendering the profile and
return it."
  (let ((buffer (profiler-report-setup-buffer-1 profile)))
    (with-current-buffer buffer
      (profiler-report-render-calltree))
    buffer))

500 501 502 503 504 505 506 507 508
(define-derived-mode profiler-report-mode special-mode "Profiler-Report"
  "Profiler Report Mode."
  (setq buffer-read-only t
	buffer-undo-list t
	truncate-lines t))


;;; Report commands

509 510
(defun profiler-report-calltree-at-point (&optional point)
  (get-text-property (or point (point)) 'calltree))
511 512

(defun profiler-report-move-to-entry ()
513 514
  (let ((point (next-single-property-change
                (line-beginning-position) 'profiler-entry)))
515 516 517 518 519
    (if point
	(goto-char point)
      (back-to-indentation))))

(defun profiler-report-next-entry ()
520
  "Move cursor to next entry."
521 522 523 524 525
  (interactive)
  (forward-line)
  (profiler-report-move-to-entry))

(defun profiler-report-previous-entry ()
526
  "Move cursor to previous entry."
527 528 529 530 531
  (interactive)
  (forward-line -1)
  (profiler-report-move-to-entry))

(defun profiler-report-expand-entry ()
532
  "Expand entry at point."
533 534 535 536 537 538 539
  (interactive)
  (save-excursion
    (beginning-of-line)
    (when (search-forward (concat profiler-report-closed-mark " ")
			  (line-end-position) t)
      (let ((tree (profiler-report-calltree-at-point)))
	(when tree
540
	  (let ((inhibit-read-only t))
541 542 543 544 545 546
	    (replace-match (concat profiler-report-open-mark " "))
	    (forward-line)
	    (profiler-report-insert-calltree-children tree)
	    t))))))

(defun profiler-report-collapse-entry ()
Paul Eggert's avatar
Paul Eggert committed
547
  "Collapse entry at point."
548 549 550 551 552 553 554 555 556 557
  (interactive)
  (save-excursion
    (beginning-of-line)
    (when (search-forward (concat profiler-report-open-mark " ")
			  (line-end-position) t)
      (let* ((tree (profiler-report-calltree-at-point))
	     (depth (profiler-calltree-depth tree))
	     (start (line-beginning-position 2))
	     d)
	(when tree
558
	  (let ((inhibit-read-only t))
559 560 561 562 563 564 565 566 567 568
	    (replace-match (concat profiler-report-closed-mark " "))
	    (while (and (eq (forward-line) 0)
			(let ((child (get-text-property (point) 'calltree)))
			  (and child
			       (numberp (setq d (profiler-calltree-depth child)))))
			(> d depth)))
	    (delete-region start (line-beginning-position)))))
      t)))

(defun profiler-report-toggle-entry ()
569 570
  "Expand entry at point if the tree is collapsed,
otherwise collapse."
571 572 573 574 575
  (interactive)
  (or (profiler-report-expand-entry)
      (profiler-report-collapse-entry)))

(defun profiler-report-find-entry (&optional event)
576
  "Find entry at point."
577
  (interactive (list last-nonmenu-event))
578 579 580 581 582 583 584 585 586
  (with-current-buffer
      (if event (window-buffer (posn-window (event-start event)))
        (current-buffer))
    (and event (setq event (event-end event))
         (posn-set-point event))
    (let ((tree (profiler-report-calltree-at-point)))
      (when tree
        (let ((entry (profiler-calltree-entry tree)))
          (find-function entry))))))
587 588

(defun profiler-report-describe-entry ()
589
  "Describe entry at point."
590 591 592 593 594 595 596
  (interactive)
  (let ((tree (profiler-report-calltree-at-point)))
    (when tree
      (let ((entry (profiler-calltree-entry tree)))
	(require 'help-fns)
	(describe-function entry)))))

597
(cl-defun profiler-report-render-calltree-1
598 599 600 601
    (profile &key reverse (order 'descending))
  (let ((calltree (profiler-calltree-build
                   (profiler-profile-log profile)
                   :reverse reverse)))
602
    (setq header-line-format
603
	  (cl-ecase (profiler-profile-type profile)
604
	    (cpu
605
	     (profiler-report-header-line-format
606
	      profiler-report-cpu-line-format
607
	      "Function" (list "CPU samples" "%")))
608
	    (memory
609 610
	     (profiler-report-header-line-format
	      profiler-report-memory-line-format
611 612 613 614 615 616
	      "Function" (list "Bytes" "%")))))
    (let ((predicate (cl-ecase order
		       (ascending #'profiler-calltree-count<)
		       (descending #'profiler-calltree-count>))))
      (profiler-calltree-sort calltree predicate))
    (let ((inhibit-read-only t))
617 618 619 620 621 622
      (erase-buffer)
      (profiler-report-insert-calltree-children calltree)
      (goto-char (point-min))
      (profiler-report-move-to-entry))))

(defun profiler-report-rerender-calltree ()
623
  (profiler-report-render-calltree-1 profiler-report-profile
624 625 626 627
				     :reverse profiler-report-reversed
				     :order profiler-report-order))

(defun profiler-report-render-calltree ()
628
  "Render calltree view."
629 630 631 632 633
  (interactive)
  (setq profiler-report-reversed nil)
  (profiler-report-rerender-calltree))

(defun profiler-report-render-reversed-calltree ()
634
  "Render reversed calltree view."
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  (interactive)
  (setq profiler-report-reversed t)
  (profiler-report-rerender-calltree))

(defun profiler-report-ascending-sort ()
  "Sort calltree view in ascending order."
  (interactive)
  (setq profiler-report-order 'ascending)
  (profiler-report-rerender-calltree))

(defun profiler-report-descending-sort ()
  "Sort calltree view in descending order."
  (interactive)
  (setq profiler-report-order 'descending)
  (profiler-report-rerender-calltree))

651 652 653 654 655 656 657 658
(defun profiler-report-profile (profile)
  (switch-to-buffer (profiler-report-setup-buffer profile)))

(defun profiler-report-profile-other-window (profile)
  (switch-to-buffer-other-window (profiler-report-setup-buffer profile)))

(defun profiler-report-profile-other-frame (profile)
  (switch-to-buffer-other-frame (profiler-report-setup-buffer profile)))
659

660 661
(defun profiler-report-compare-profile (buffer)
  "Compare the current profile with another."
662
  (interactive (list (read-buffer "Compare to: ")))
663 664 665 666
  (let* ((profile1 (with-current-buffer buffer profiler-report-profile))
	 (profile2 profiler-report-profile)
	 (diff-profile (profiler-compare-profiles profile1 profile2)))
    (profiler-report-profile diff-profile)))
667

668 669
(defun profiler-report-write-profile (filename &optional confirm)
  "Write the current profile into file FILENAME."
670
  (interactive
671
   (list (read-file-name "Write profile: " default-directory)
672
	 (not current-prefix-arg)))
673 674 675
  (profiler-write-profile profiler-report-profile
                          filename
                          confirm))
676 677 678 679 680 681


;;; Profiler commands

;;;###autoload
(defun profiler-start (mode)
682 683 684 685
  "Start/restart profilers.
MODE can be one of `cpu', `mem', or `cpu+mem'.
If MODE is `cpu' or `cpu+mem', time-based profiler will be started.
Also, if MODE is `mem' or `cpu+mem', then memory profiler will be started."
686
  (interactive
687 688 689 690
   (list (if (not (fboundp 'profiler-cpu-start)) 'mem
           (intern (completing-read "Mode (default cpu): "
                                    '("cpu" "mem" "cpu+mem")
                                    nil t nil nil "cpu")))))
691
  (cl-ecase mode
692
    (cpu
693
     (profiler-cpu-start profiler-sampling-interval)
694
     (message "CPU profiler started"))
695
    (mem
696
     (profiler-memory-start)
697
     (message "Memory profiler started"))
698
    (cpu+mem
699
     (profiler-cpu-start profiler-sampling-interval)
700
     (profiler-memory-start)
701 702 703
     (message "CPU and memory profiler started"))))

(defun profiler-stop ()
704
  "Stop started profilers.  Profiler logs will be kept."
705
  (interactive)
706 707 708 709 710 711 712
  (let ((cpu (if (fboundp 'profiler-cpu-stop) (profiler-cpu-stop)))
        (mem (profiler-memory-stop)))
    (message "%s profiler stopped"
             (cond ((and mem cpu) "CPU and memory")
                   (mem "Memory")
                   (cpu "CPU")
                   (t "No")))))
713 714

(defun profiler-reset ()
715
  "Reset profiler logs."
716
  (interactive)
717 718
  (when (fboundp 'profiler-cpu-log)
    (ignore (profiler-cpu-log)))
719
  (ignore (profiler-memory-log))
720 721
  t)

722 723 724 725
(defun profiler-report-cpu ()
  (let ((profile (profiler-cpu-profile)))
    (when profile
      (profiler-report-profile-other-window profile))))
726

727 728 729 730
(defun profiler-report-memory ()
  (let ((profile (profiler-memory-profile)))
    (when profile
      (profiler-report-profile-other-window profile))))
731

732
(defun profiler-report ()
733
  "Report profiling results."
734
  (interactive)
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
  (profiler-report-cpu)
  (profiler-report-memory))

;;;###autoload
(defun profiler-find-profile (filename)
  "Open profile FILENAME."
  (interactive
   (list (read-file-name "Find profile: " default-directory)))
  (profiler-report-profile (profiler-read-profile filename)))

;;;###autoload
(defun profiler-find-profile-other-window (filename)
  "Open profile FILENAME."
  (interactive
   (list (read-file-name "Find profile: " default-directory)))
  (profiler-report-profile-other-window (profiler-read-profile filename)))
751

752
;;;###autoload
753 754
(defun profiler-find-profile-other-frame (filename)
  "Open profile FILENAME."
755
  (interactive
756 757
   (list (read-file-name "Find profile: " default-directory)))
  (profiler-report-profile-other-frame(profiler-read-profile filename)))
758

759 760 761

;;; Profiling helpers

762
;; (cl-defmacro with-cpu-profiling ((&key sampling-interval) &rest body)
Stefan Monnier's avatar
Stefan Monnier committed
763 764 765
;;   `(unwind-protect
;;        (progn
;;          (ignore (profiler-cpu-log))
766
;;          (profiler-cpu-start ,sampling-interval)
Stefan Monnier's avatar
Stefan Monnier committed
767 768 769 770 771 772 773 774 775 776 777 778
;;          ,@body)
;;      (profiler-cpu-stop)
;;      (profiler--report-cpu)))

;; (defmacro with-memory-profiling (&rest body)
;;   `(unwind-protect
;;        (progn
;;          (ignore (profiler-memory-log))
;;          (profiler-memory-start)
;;          ,@body)
;;      (profiler-memory-stop)
;;      (profiler--report-memory)))
779

780 781
(provide 'profiler)
;;; profiler.el ends here