Updated 2012-04-25 01:46:56 by RLE

Richard Suchenwirth 2005-11-16 - Hunting for leaks in our software, I could not use the TCL_MEM_DEBUG mechanism. But the following code gives an approximate size in bytes consumed by the variables and children of a Tcl namespace (of which ::, the global namespace, is of particular interest - all its (grand)*children are also added). If you call this proc repeatedly, you can observe whether data are piling up:
 proc namespace'size ns {
   set sum [expr wide(0)]
   foreach var [info vars ${ns}::*] {
       if {[info exists $var]} {
           upvar #0 $var v
           if {[array exists v]} {
               incr sum [string bytelength [array get v]]
           } else {
               incr sum [string bytelength $v]
           }
       }
   }
   foreach child [namespace children $ns] {
       incr sum [namespace'size $child]
   }
   set sum
 }

Usage example:
 % puts [namespace'size ::]
 179914

JMN 2005-11-16 Modified (added 'info exists $var' if block) to account for case where var 'exists' but has not been initialised - e.g., namespace eval ::something {variable x}

jcw - By adding at least 1 more for each var/array seen, you'd also catch empty ones. Real memory use cannot easily be determined this way though, since the dual representation of values is not considered with this approach. - RS agrees; the question that led to this was: if we process, say, several thousand items, does the size stay constant, or increase significantly?