tags:

views:

38

answers:

2

I would like to know how much physical memory is available on the system, excluding any swap. Is there a method to get this information in Ruby?

A: 

Well, the Unix command "top" doesn't seem to work in Ruby, so try this:

# In Kilobytes
memory_usages = `ps -A -o rss=`.split("\n")
total_mem_usage = memory_usages.inject { |a, e| a.to_i + e.strip.to_i }

This "seems" correct. I don't guarantee it. Also, this takes a lot more time than the system will so by the time it's finished the physical memory would have changed.

AndrewKS
After some testing, it seems legitimate.
AndrewKS
+1  A: 

If you are using linux,You usually use a "free" command to find physical memory ie RAM details on the system

 output = %x(free)

output will look slightly like the following string

" total used free shared buffers cached\nMem: 251308 201500 49808 0 3456 48508\n-/+ buffers/cache: 149536 101772\nSwap: 524284 88612 435672\n"

You can extract the information you need using simple string manipulations like

output.split(" ")[7] will give total memory output.split(" ")[8] will give used memory output.split(" ")[9] will give free memory

Rishav Rastogi
look good, I am going to try it.
Guillaume Coté
Working fine, thanks
Guillaume Coté