Skip to content

Instantly share code, notes, and snippets.

@fcheung
Created July 5, 2019 22:13
Show Gist options
  • Save fcheung/4304b71d14ad4b428b781996bec31a25 to your computer and use it in GitHub Desktop.
Save fcheung/4304b71d14ad4b428b781996bec31a25 to your computer and use it in GitHub Desktop.
get_process_mem
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
@fcheung
Copy link
Author

fcheung commented Jul 5, 2019

output on my machine

Warming up --------------------------------------
     get_process_mem    28.000  i/100ms
           task_info    22.294k i/100ms
Calculating -------------------------------------
     get_process_mem    343.306  (± 3.8%) i/s -      1.736k in   5.064142s
           task_info    252.462k (± 3.2%) i/s -      1.271M in   5.038761s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment