2013-07-18 14 views
8

私のPythonスクリプトで空きRAMをすべて使用できるようにしたいと思いますが、それ以上の理由はありません(効率上の理由から)。限られた量のデータだけを読み込むことでこれを制御できますが、この権利を得るには実行時にRAMの空き容量を知る必要があります。これは、さまざまなLinuxシステム上で実行されます。実行時に空きRAMを判断することは可能ですか?Pythonで空きRAMを確認する

答えて

5

ちょうど/proc/meminfoを読むことができます。 OSはキャッシュ用に空きの未使用メモリを頻繁に使用するため、「空きメモリ」は通常かなり低いことに注意してください。

また、OSのメモリ管理を圧倒しないようにしてください。それは通常、涙(または遅いプログラム)で終わります。あなたが必要とするRAMを取るほうがいい。以前に未知の量のメモリがあるマシンでできるだけ多くのRAMを使用したい場合は、インストールされているRAMの量(MemTotal/proc/meminfo)で確認してください。 1 GB)、残りの部分を使用してください。

+1

いくつかの* nixシステムは、/ procなしで提供されています。( – nic

+2

@nic '/ proc/meminfo'は、現在の値のセット[少なくともLinux 2.6以降で利用可能です。](http://linux.die.net/man/ – Carsten

+1

Linux以外の* nixシステムがあるので、汎用性のためにこれについて言及しておきます。 – nic

0

私はあなたがこれを行うには私の答えの最下部に掲載SO-スレッドから多分無料http://www.cyberciti.biz/faq/linux-check-memory-usage/)、PSまたはMemoryMonitorクラスを使用する可能性があるとします。いくつかのスラックをカットして、他のプロセスで使用されていない少量のRAMを残しておいてください。

出力をfreeまたはpsから解析する必要がありますが、それを使用する場合は難しくありません。利用可能なRAMをリアルタイムで分析する必要があることを覚えておいてください。何らかの理由で他のプロセスが空き領域を確保できるかどうかを調整できます。

も、このスレッドを参照してください。私は時々これを使用するLinuxシステムでは How to get current CPU and RAM usage in Python?

15

def memory(): 
    """ 
    Get node total memory and memory usage 
    """ 
    with open('/proc/meminfo', 'r') as mem: 
     ret = {} 
     tmp = 0 
     for i in mem: 
      sline = i.split() 
      if str(sline[0]) == 'MemTotal:': 
       ret['total'] = int(sline[1]) 
      elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'): 
       tmp += int(sline[1]) 
     ret['free'] = tmp 
     ret['used'] = int(ret['total']) - int(ret['free']) 
    return ret 

スクリプトが起動するときは、これを実行することができます。 RAMは通常、使用頻度の高いシステムで使用され、かなり頻繁に解放されるため、使用するRAMの量を決定する前に考慮する必要があります。また、ほとんどのLinuxシステムでは、swappiness値が60です。メモリーを使い果たすと、最も頻繁に使用されないページがスワップアウトされます。 RAMの代わりにSWAPを使用しているかもしれません。

これが役に立ちます。

+0

60のswappiness値はどういう意味ですか? – marshall

+0

@ marshall http://askubuntu.com/questions/103915/how-do-i-configure-swappinessは公正な口座を提供します。 – nic

+0

カーネルがページをスワップアウトする可能性があります。値の範囲は0〜100です.0は最もスワップアウトされない可能性があります(通常はメモリー不足の状態を回避するためにこれを行います)。100は積極的なスワッピングです。 –

3

オリジナルポスターは、コードがのLinuxシステムのさまざまな実行する必要が書いたので、私はここでは、Linuxのメモリー・クエリのためのオブジェクト指向のソリューションを掲示しています。 psutil は偉大なライブラリですが、あなたには、いくつかの理由のためにそれをインストールすることはできません場合は、単に以下のソリューションを使用することができます。

使用例:

>>> f = FreeMemLinux() 
>>> print f.total, f.used, f.user_free 
8029212 3765960 4464816 
>>> 
>>> f_mb = FreeMemLinux(unit='MB') 
>>> print f_mb.total, f_mb.used, f_mb.user_free 
7841.02734375 3677.6953125 4360.171875 
>>> 
>>> f_percent = FreeMemLinux(unit='%') 
>>> print f_percent.total, f_percent.used, f_percent.user_free 
100.0 46.9032328453 55.60715049 

はコード:

class FreeMemLinux(object): 
    """ 
    Non-cross platform way to get free memory on Linux. Note that this code 
    uses the `with ... as`, which is conditionally Python 2.5 compatible! 
    If for some reason you still have Python 2.5 on your system add in the 
head of your code, before all imports: 
    from __future__ import with_statement 
    """ 

    def __init__(self, unit='kB'): 

     with open('/proc/meminfo', 'r') as mem: 
      lines = mem.readlines() 

     self._tot = int(lines[0].split()[1]) 
     self._free = int(lines[1].split()[1]) 
     self._buff = int(lines[2].split()[1]) 
     self._cached = int(lines[3].split()[1]) 
     self._shared = int(lines[20].split()[1]) 
     self._swapt = int(lines[14].split()[1]) 
     self._swapf = int(lines[15].split()[1]) 
     self._swapu = self._swapt - self._swapf 

     self.unit = unit 
     self._convert = self._factor() 

    def _factor(self): 
     """determine the convertion factor""" 
     if self.unit == 'kB': 
      return 1 
     if self.unit == 'k': 
      return 1024.0 
     if self.unit == 'MB': 
      return 1/1024.0 
     if self.unit == 'GB': 
      return 1/1024.0/1024.0 
     if self.unit == '%': 
      return 1.0/self._tot 
     else: 
      raise Exception("Unit not understood") 

    @property 
    def total(self): 
     return self._convert * self._tot 

    @property 
    def used(self): 
     return self._convert * (self._tot - self._free) 

    @property 
    def used_real(self): 
     """memory used which is not cache or buffers""" 
     return self._convert * (self._tot - self._free - 
           self._buff - self._cached) 

    @property 
    def shared(self): 
     return self._convert * (self._tot - self._free) 

    @property 
    def buffers(self): 
     return self._convert * (self._buff) 

    @property 
    def cached(self): 
     return self._convert * self._cached 

    @property 
    def user_free(self): 
     """This is the free memory available for the user""" 
     return self._convert *(self._free + self._buff + self._cached) 

    @property 
    def swap(self): 
     return self._convert * self._swapt 

    @property 
    def swap_free(self): 
     return self._convert * self._swapf 

    @property 
    def swap_used(self): 
     return self._convert * self._swapu 
関連する問題