Created
July 5, 2019 22:13
-
-
Save fcheung/4304b71d14ad4b428b781996bec31a25 to your computer and use it in GitHub Desktop.
get_process_mem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ffi' | |
require 'get_process_mem' | |
require 'benchmark/ips' | |
module MemoryInfo | |
extend FFI::Library | |
ffi_lib 'c' | |
attach_function :mach_task_self, [], :__darwin_mach_port_t | |
attach_function :task_info, | |
[ | |
:__darwin_mach_port_t, | |
:int, | |
:pointer, #pointer to task info | |
:pointer, #pointer to int | |
], | |
:int | |
class TaskInfo < FFI::Struct | |
layout :suspend_count, :int32, | |
:virtual_size, :uint64, | |
:resident_size, :uint64, | |
:user_time, :uint64, | |
:system_time, :uint64, | |
:int32, :int32 | |
end | |
MACH_TASK_BASIC_INFO = 20 | |
MACH_TASK_BASIC_INFO_COUNT = TaskInfo.size / FFI.type_size(:uint) | |
class << self | |
def resident_size | |
get_task_info[:resident_size] | |
end | |
private | |
def get_task_info | |
data = TaskInfo.new | |
out_count = FFI::MemoryPointer.new(:int, 1) | |
out_count.write(:uint, MACH_TASK_BASIC_INFO_COUNT) | |
result = task_info(mach_task_self, MACH_TASK_BASIC_INFO, data, out_count) | |
if result == 0 | |
data | |
else | |
raise "task_info returned #{result}" | |
end | |
end | |
end | |
end | |
Benchmark.ips do |x| | |
x.report(:get_process_mem) { GetProcessMem.new.bytes} | |
x.report(:task_info) { MemoryInfo.resident_size} | |
end | |
puts GetProcessMem.new.bytes.to_i | |
puts MemoryInfo.resident_size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output on my machine