How do you find physical memory free on a machine in Ruby?

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

+7
source share
6 answers

If you use linux, you usually use the "free" command to search for physical memory, that is, information about RAM in the system

 output =% x (free)

the output will look a bit like this:

" 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 necessary information using simple string manipulations, for example

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

+10
source

AndrewKS:

total_memory_usage_in_k = `ps -Ao rss=`.split.map(&:to_i).inject(&:+)
+4

, Unix "top", , Ruby, :

# 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 }

"" . . , , , .

+3

Ruby, Bash , , Python :

#!/usr/bin/env bash 
# This file is in public domain. 
# Initial author: martin.vahi@softf1.com

#export S_MEMINFO_FIELD="Inactive"; \
export S_MEMINFO_FIELD="MemTotal"; \
ruby -e "s=%x(cat /proc/meminfo | grep $S_MEMINFO_FIELD: | \
gawk '{gsub(/MemTotal:/,\"\");print}' | \
gawk '{gsub(/kB/,\"*1024\");print}' | \
gawk '{gsub(/KB/,\"*1024\");print}' | \
gawk '{gsub(/KiB/,\"*1024\");print}' | \
gawk '{gsub(/MB/,\"*1048576\");print}' | \
gawk '{gsub(/MiB/,\"*1048576\");print}' | \
gawk '{gsub(/GB/,\"*1073741824\");print}' | \
gawk '{gsub(/GiB/,\"*1073741824\");print}' | \
gawk '{gsub(/TB/,\"*1099511627776\");print}' | \
gawk '{gsub(/TiB/,\"*1099511627776\");print}' | \
gawk '{gsub(/B/,\"*1\");print}' | \
gawk '{gsub(/[^1234567890*]/,\"\");print}' \
); \
s_prod=s.gsub(/[\\s\\n\\r]/,\"\")+\"*1\";\
ar=s_prod.scan(/[\\d]+/);\
i_prod=1;\
ar.each{|s_x| i_prod=i_prod*s_x.to_i};\
print(i_prod.to_s+\" B\")"

, "\" Bash . , , , .

grep $S_MEMINFO_FIELD:

,

cat /proc/meminfo | grep Inactive

, script , grep .

https://unix.stackexchange.com/questions/263881/convert-meminfo-kb-to-bytes

/proc/meminfo 1024 , "kB" "KB". GiB GB TB, , 1MB = 1024 * 1024KiB.

Linux Bash script, /proc/meminfo 1. :

http://longterm.softf1.com/2016/comments/stackoverflow_com/2016_03_07_mmmv_proc_meminfo_filter_t1.bash

( : https://archive.is/vjcNf)

, . , .: -)

+1
source

You can use a common gem (I'm the author):

require 'total'
puts Total::Mem.new.bytes
0
source

All Articles