Skip to content →

Getting used heap space in Allegro CL (and other Lisps)

If you’re running experiments in Lisp and want to know the total amount of memory currently in use (i.e., by live objects), it’s much less straightforward than you might think. The following code gets this number in a handful of different Lisps. Some of the cases are borrowed from this file from McCLIM. My contribution is the case for Allegro CL, which uses non-public information on its internals that I obtained directly from Franz Inc. They assure me that there’s (unfortunately) currently no better way to do this.

; Number of bytes-per-cons in ACL; TODO: if 64-bit, should be 16
(defconstant +allegro-cons-bytes+ 8 )  

(defun dynamic-usage ()
  "Get the number of live bytes on the heap, or 0 if unsupported.  May be quite slow."
  #+(or cmu scl) (lisp::dynamic-usage)
  #+sbcl         (sb-kernel:dynamic-usage)
  #+lispworks    (getf (system:room-values) :total-allocated)
  #+openmcl      (+ (ccl::%usedbytes) (ccl::%freebytes))
  #+clisp        (values (sys::%room))
  #+allegro      
      ;; sys::gsgc-map is an unsupported internal function in Allegro CL
      ;; which may (Franz Inc. points out) be modified or removed 
      ;; without notice.  Tested and working in Allegro 6.2 and 8.0.
     (let ((data (sys::gsgc-map 1))) ; Tested in 6.2 and 8.0.
       (loop for i from 23 to (length data) by 10 ; loop through oldspaces summing
          summing (aref data i) into conses      ;   number of oldspace conses
          summing (aref data (+ i 6)) into bytes ;   additional oldspace bytes
          finally                   ; and return total bytes (including newspace)
        (return (+ (* +allegro-cons-bytes+  (+ (aref data 3) conses)) 
                   (+ (aref data 9) bytes)))))
  #-(or cmu scl sbcl lispworks openmcl clisp allegro) 0)

If you want accurate counts, be sure to run a global GC (or two) first.

Published in Lisp

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *