Ruby ขอหน่วยความจำเป็น chunks เรียกว่า pages ใช้ malloc จาก OS มี alternative implementations เช่น Google's tcmalloc (ส่วนของ Google Performance Tools) ใช้ LD_PRELOAD แทนที่ system malloc
LD_PRELOAD="/usr/lib/libtcmalloc.so" ruby -e "puts 123"
Enabling The Profiler
เปิด profiler ด้วย HEAPPROFILE:
LD_PRELOAD="/usr/lib/libtcmalloc.so" HEAPPROFILE=/tmp/profile ruby -e "puts 123"
อ่านไฟล์ผลลัพธ์ด้วย pprof:
pprof --text `which ruby` /tmp/profile.0001.heap | head -10
ต้องใช้ Ruby ที่ compile ดับ debug symbols เพื่อเห็น function names แทน memory addresses
ผลลัพธ์แสดง memory allocated โดย MRI functions: aligned_malloc (allocate pages), stack_chunk_alloc (GC marking), objspace_xmalloc0/objspace_xcalloc (strings, arrays)
Visualization:
pprof --web `which ruby` /tmp/profile.0001.heap
เปิด browser แสดง SVG call graph TCMalloc เพิ่ม performance 4-9% อีกด้วย ลอง jemalloc ได้อีกตัว
Summary
เรียนรู้ใช้ gperftools (Google Performance Tools) visualize และ analyze memory usage ของ Ruby interpreter