Skip to content

Instantly share code, notes, and snippets.

@scottjg
Created January 13, 2013 00:12
Show Gist options
  • Save scottjg/4521186 to your computer and use it in GitHub Desktop.
Save scottjg/4521186 to your computer and use it in GitHub Desktop.
Forces Ruby GC to compact the tcmalloc heap after garbage collecting
#include <ruby.h>
#include <stdlib.h>
#include <stdio.h>
#include <node.h>
#include <dlfcn.h>
void (*ReleaseFreeMemory)(void);
#ifdef RUBY_GC_EVENT_ALL
// requires https://github.com/tmm1/brew2deb/blob/master/packages/ruby/patches/gc-hooks.patch
static void gc_hook(rb_gc_event_t gc_event, VALUE obj)
{
switch(gc_event)
{
case RUBY_GC_EVENT_END:
ReleaseFreeMemory();
break;
}
}
#endif
void Init_heap_compactor_ext()
{
#ifndef RUBY_GC_EVENT_ALL
rb_raise(rb_eNotImpError, "rb_gc_add_event_hook() is not available in this ruby build");
#else
ReleaseFreeMemory = dlsym(RTLD_DEFAULT, "MallocExtension_ReleaseFreeMemory");
if (ReleaseFreeMemory == NULL)
rb_raise(rb_eNotImpError, "tcmalloc is not linked in this ruby build");
rb_gc_add_event_hook(gc_hook, RUBY_GC_EVENT_END);
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment