| 1 |
#include "ruby.h" |
| 2 |
#ifdef __APPLE__ |
| 3 |
# include <mach/mach.h> |
| 4 |
# include <mach/message.h> |
| 5 |
# include <mach/kern_return.h> |
| 6 |
# include <mach/task_info.h> |
| 7 |
#elif defined _WIN32 |
| 8 |
# include <psapi.h> |
| 9 |
#endif |
| 10 |
|
| 11 |
static VALUE cMemoryStatus; |
| 12 |
|
| 13 |
#undef HAVE_RSS |
| 14 |
#undef HAVE_PEAK |
| 15 |
|
| 16 |
static VALUE |
| 17 |
read_status(VALUE self) |
| 18 |
{ |
| 19 |
VALUE size = INT2FIX(0); |
| 20 |
#if defined __APPLE__ |
| 21 |
# define HAVE_RSS 1 |
| 22 |
VALUE rss; |
| 23 |
kern_return_t error; |
| 24 |
# if defined MACH_TASK_BASIC_INFO |
| 25 |
const task_flavor_t flavor = MACH_TASK_BASIC_INFO; |
| 26 |
mach_msg_type_number_t out_count = MACH_TASK_BASIC_INFO_COUNT; |
| 27 |
mach_task_basic_info_data_t taskinfo; |
| 28 |
# else |
| 29 |
const task_flavor_t flavor = TASK_BASIC_INFO; |
| 30 |
mach_msg_type_number_t out_count = TASK_BASIC_INFO_COUNT; |
| 31 |
task_basic_info_data_t taskinfo; |
| 32 |
# endif |
| 33 |
|
| 34 |
taskinfo.virtual_size = 0; |
| 35 |
taskinfo.resident_size = 0; |
| 36 |
error = task_info(mach_task_self(), flavor, |
| 37 |
(task_info_t)&taskinfo, &out_count); |
| 38 |
if (error != KERN_SUCCESS) return Qnil; |
| 39 |
#ifndef ULL2NUM |
| 40 |
/* "long long" does not exist here, use size_t instead. */ |
| 41 |
#define ULL2NUM SIZET2NUM |
| 42 |
#endif |
| 43 |
size = ULL2NUM(taskinfo.virtual_size); |
| 44 |
rss = ULL2NUM(taskinfo.resident_size); |
| 45 |
rb_struct_aset(self, INT2FIX(1), rss); |
| 46 |
#elif defined _WIN32 |
| 47 |
# define HAVE_RSS 1 |
| 48 |
# define HAVE_PEAK 1 |
| 49 |
VALUE rss, peak; |
| 50 |
PROCESS_MEMORY_COUNTERS c; |
| 51 |
c.cb = sizeof(c); |
| 52 |
if (!GetProcessMemoryInfo(GetCurrentProcess(), &c, c.cb)) |
| 53 |
return Qnil; |
| 54 |
size = SIZET2NUM(c.PagefileUsage); |
| 55 |
rss = SIZET2NUM(c.WorkingSetSize); |
| 56 |
peak = SIZET2NUM(c.PeakWorkingSetSize); |
| 57 |
rb_struct_aset(self, INT2FIX(2), peak); |
| 58 |
#endif |
| 59 |
#ifdef HAVE_RSS |
| 60 |
rb_struct_aset(self, INT2FIX(1), rss); |
| 61 |
#endif |
| 62 |
rb_struct_aset(self, INT2FIX(0), size); |
| 63 |
return self; |
| 64 |
} |
| 65 |
|
| 66 |
void |
| 67 |
Init_memory_status(void) |
| 68 |
{ |
| 69 |
VALUE mMemory = rb_define_module("Memory"); |
| 70 |
cMemoryStatus = |
| 71 |
rb_struct_define_under(mMemory, "Status", "size", |
| 72 |
#ifdef HAVE_RSS |
| 73 |
"rss", |
| 74 |
#endif |
| 75 |
#ifdef HAVE_PEAK |
| 76 |
"peak", |
| 77 |
#endif |
| 78 |
(char *)NULL); |
| 79 |
rb_define_method(cMemoryStatus, "_update", read_status, 0); |
| 80 |
} |