Determine memory specifications of the machine.

    Returns
    -------
    mem_info : dictonary
        Holds the current values for the total, free and used memory of the system.
342432
def memory():
    

    mem_info = dict()

    for k, v in psutil.virtual_memory()._asdict().items():
           mem_info[k] = int(v)
           
    return mem_info
951771
def vm_info(vm_=None):
    '''
    
    '''
    with _get_xapi_session() as xapi:

        def _info(vm_):
            vm_rec = _get_record_by_label(xapi, 'VM', vm_)
            if vm_rec is False:
                return False
            vm_metrics_rec = _get_metrics_record(xapi, 'VM', vm_rec)

            return {'cpu': vm_metrics_rec['VCPUs_number'],
                    'maxCPU': _get_val(vm_rec, ['VCPUs_max']),
                    'cputime': vm_metrics_rec['VCPUs_utilisation'],
                    'disks': get_disks(vm_),
                    'nics': get_nics(vm_),
                    'maxMem': int(_get_val(vm_rec, ['memory_dynamic_max'])),
                    'mem': int(vm_metrics_rec['memory_actual']),
                    'state': _get_val(vm_rec, ['power_state'])
                    }
        info = {}
        if vm_:
            ret = _info(vm_)
            if ret is not None:
                info[vm_] = ret
        else:
            for vm_ in list_domains():
                ret = _info(vm_)
                if ret is not None:
                    info[vm_] = _info(vm_)
        return info
235525
def meminfo():
    '''
    
    '''
    def linux_meminfo():
        '''
        linux specific implementation of meminfo
        '''
        ret = {}
        try:
            with salt.utils.files.fopen('/proc/meminfo', 'r') as fp_:
                stats = salt.utils.stringutils.to_unicode(fp_.read())
        except IOError:
            pass
        else:
            for line in stats.splitlines():
                if not line:
                    continue
                comps = line.split()
                comps[0] = comps[0].replace(':', '')
                ret[comps[0]] = {
                    'value': comps[1],
                }
                if len(comps) > 2:
                    ret[comps[0]]['unit'] = comps[2]
        return ret

    def freebsd_meminfo():
        '''
        freebsd specific implementation of meminfo
        '''
        sysctlvm = __salt__['cmd.run']('sysctl vm').splitlines()
        sysctlvm = [x for x in sysctlvm if x.startswith('vm')]
        sysctlvm = [x.split(':') for x in sysctlvm]
        sysctlvm = [[y.strip() for y in x] for x in sysctlvm]
        sysctlvm = [x for x in sysctlvm if x[1]]  # If x[1] not empty

        ret = {}
        for line in sysctlvm:
            ret[line[0]] = line[1]
        # Special handling for vm.total as it's especially important
        sysctlvmtot = __salt__['cmd.run']('sysctl -n vm.vmtotal').splitlines()
        sysctlvmtot = [x for x in sysctlvmtot if x]
        ret['vm.vmtotal'] = sysctlvmtot
        return ret

    def aix_meminfo():
        '''
        AIX specific implementation of meminfo
        '''
        ret = {}
        ret['svmon'] = []
        ret['vmstat'] = []
        procn = None
        fields = []
        pagesize_flag = False
        for line in __salt__['cmd.run']('svmon -G').splitlines():
            # Note: svmon is per-system
            #               size       inuse        free         pin     virtual   mmode
            #memory      1048576     1039740        8836      285078      474993     Ded
            #pg space     917504        2574
            #
            #               work        pers        clnt       other
            #pin          248379           0        2107       34592
            #in use       474993           0      564747
            #
            #PageSize   PoolSize       inuse        pgsp         pin     virtual
            #s    4 KB         -      666956        2574       60726      102209
            #m   64 KB         -       23299           0       14022       23299
            if not line:
                continue

            if re.match(r'\s', line):
                # assume fields line
                fields = line.split()
                continue

            if line.startswith('memory') or line.startswith('pin'):
                procn = len(ret['svmon'])
                ret['svmon'].append({})
                comps = line.split()
                ret['svmon'][procn][comps[0]] = {}
                for i in range(0, len(fields)):
                    if len(comps) > i + 1:
                        ret['svmon'][procn][comps[0]][fields[i]] = comps[i+1]
                continue

            if line.startswith('pg space') or line.startswith('in use'):
                procn = len(ret['svmon'])
                ret['svmon'].append({})
                comps = line.split()
                pg_space = '{0} {1}'.format(comps[0], comps[1])
                ret['svmon'][procn][pg_space] = {}
                for i in range(0, len(fields)):
                    if len(comps) > i + 2:
                        ret['svmon'][procn][pg_space][fields[i]] = comps[i+2]
                continue

            if line.startswith('PageSize'):
                fields = line.split()
                pagesize_flag = False
                continue

            if pagesize_flag:
                procn = len(ret['svmon'])
                ret['svmon'].append({})
                comps = line.split()
                ret['svmon'][procn][comps[0]] = {}
                for i in range(0, len(fields)):
                    if len(comps) > i:
                        ret['svmon'][procn][comps[0]][fields[i]] = comps[i]
                continue

        for line in __salt__['cmd.run']('vmstat -v').splitlines():
            # Note: vmstat is per-system
            if not line:
                continue

            procn = len(ret['vmstat'])
            ret['vmstat'].append({})
            comps = line.lstrip().split(' ', 1)
            ret['vmstat'][procn][comps[1]] = comps[0]

        return ret

    def openbsd_meminfo():
        '''
        openbsd specific implementation of meminfo
        '''
        vmstat = __salt__['cmd.run']('vmstat').splitlines()
        # We're only interested in memory and page values which are printed
        # as subsequent fields.
        fields = ['active virtual pages', 'free list size', 'page faults',
                  'pages reclaimed', 'pages paged in', 'pages paged out',
                  'pages freed', 'pages scanned']
        data = vmstat[2].split()[2:10]
        ret = dict(zip(fields, data))
        return ret

    # dict that return a function that does the right thing per platform
    get_version = {
        'Linux': linux_meminfo,
        'FreeBSD': freebsd_meminfo,
        'OpenBSD': openbsd_meminfo,
        'AIX': aix_meminfo,
    }

    errmsg = 'This method is unsupported on the current operating system!'
    return get_version.get(__grains__['kernel'], lambda: errmsg)()
629770
def read_meminfo():
    
    data = {}
    with open("/proc/meminfo", "rb") as meminfo_file:
        for row in meminfo_file:
            fields = row.split()
            # Example content:
            # MemTotal:                3801016 kB
            # MemFree:                 1840972 kB
            # MemAvailable:        3287752 kB
            # HugePages_Total:             0
            data[fields[0].decode("ascii")[:-1]] = int(fields[1]) * 1024
    return data
318134
def get_initial_RAM(self):
        
        mem_FF = [0xff for _ in xrange(4)]
        mem_00 = [0x00 for _ in xrange(4)]

        mem = []
        for _ in xrange(self.RAM_SIZE // 8):
            mem += mem_FF
            mem += mem_00

        return mem
266728
def get_memfree(memory, parallel):
  """"""
  number = int(memory.rstrip(string.ascii_letters))
  memtype = memory.lstrip(string.digits)
  if not memtype:
    memtype = "G"
  return "%d%s" % (number*parallel, memtype)
446123
def _memory_data(self, log_prefix):
        
        machine_data = psutil.virtual_memory()

        process = psutil.Process()
        process_data = {
            'memory_info': process.get_memory_info(),
            'ext_memory_info': process.get_ext_memory_info(),
            'memory_percent': process.get_memory_percent(),
            'cpu_percent': process.get_cpu_percent(),
        }

        log.info(u"%s Machine memory usage: %s; Process memory usage: %s", log_prefix, machine_data, process_data)
        return {
            'machine_data': machine_data,
            'process_data': process_data,
        }
185140
def getMemoryStats(self):
        
        if self._statusxml is None:
            self.initStats()
        node = self._statusxml.find('jvm/memory')
        memstats = {}
        if node is not None:
            for (key,val) in node.items():
                memstats[key] = util.parse_value(val)
        return memstats
542178
def _calc_mem_info(self, unit, meminfo, memory):
        
        if memory:
            total_mem_kib = meminfo["MemTotal:"]
            used_mem_kib = (
                total_mem_kib
                - meminfo["MemFree:"]
                - (
                    meminfo["Buffers:"]
                    + meminfo["Cached:"]
                    + (meminfo["SReclaimable:"] - meminfo["Shmem:"])
                )
            )
        else:
            total_mem_kib = meminfo["SwapTotal:"]
            used_mem_kib = total_mem_kib - meminfo["SwapFree:"]

        used_percent = 100 * used_mem_kib / total_mem_kib

        unit = "B" if unit == "dynamic" else unit
        (total, total_unit) = self.py3.format_units(total_mem_kib * 1024, unit)
        (used, used_unit) = self.py3.format_units(used_mem_kib * 1024, unit)
        return total, total_unit, used, used_unit, used_percent
567034
def check_mem_usage(soft_percent=None, hard_percent=None):
    
    soft_percent = soft_percent or config.memory.soft_mem_limit
    hard_percent = hard_percent or config.memory.hard_mem_limit
    used_mem_percent = psutil.virtual_memory().percent
    if used_mem_percent > hard_percent:
        raise MemoryError('Using more memory than allowed by configuration '
                          '(Used: %d%% / Allowed: %d%%)! Shutting down.' %
                          (used_mem_percent, hard_percent))
    elif used_mem_percent > soft_percent:
        msg = 'Using over %d%% of the memory in %s!'
        return msg % (used_mem_percent, socket.gethostname())
559173
def get_info(self):
        '''
        
        '''
        if not self.info:
            ci = win32pdh.GetCounterInfo(self.handle, 0)
            self.info = {
                'type': ci[0],
                'version': ci[1],
                'scale': ci[2],
                'default_scale': ci[3],
                'user_data': ci[4],
                'query_user_data': ci[5],
                'full_path': ci[6],
                'machine_name': ci[7][0],
                'object_name': ci[7][1],
                'instance_name': ci[7][2],
                'parent_instance': ci[7][3],
                'instance_index': ci[7][4],
                'counter_name': ci[7][5],
                'explain_text': ci[8]
            }
        return self.info
127837
def memory():
    '''
    
    '''

    # test defaults
    # --memory-block-size = 10M
    # --memory-total-size = 1G

    # We test memory read / write against global / local scope of memory
    # Test data
    memory_oper = ['read', 'write']
    memory_scope = ['local', 'global']

    # Initializing the test variables
    test_command = 'sysbench --num-threads=64 --test=memory '
    test_command += '--memory-oper={0} --memory-scope={1} '
    test_command += '--memory-block-size=1K --memory-total-size=32G run '
    result = None
    ret_val = {}

    # Test begins!
    for oper in memory_oper:
        for scope in memory_scope:
            key = 'Operation: {0} Scope: {1}'.format(oper, scope)
            run_command = test_command.format(oper, scope)
            result = __salt__['cmd.run'](run_command)
            ret_val[key] = _parser(result)

    return ret_val
132373
protected function getSystemMemoryInfo()
    {
        $meminfo = array();

        if (file_exists(static::MEMINFO_PATH)) {
            $data = explode("\n", file_get_contents(static::MEMINFO_PATH));
            $meminfo = array();
            foreach ($data as $line) {
                if (!empty($line)) {
                    list($key, $val) = explode(":", $line);

                    $meminfo[$key] = intval($val);
                }
            }
        }

        return $meminfo;
    }
1350089
def memory_usage():
    
    try:
        import psutil
        import os
    except ImportError:
        return _memory_usage_ps()

    process = psutil.Process(os.getpid())
    mem = process.memory_info()[0] / float(2 ** 20)
    return mem
1090583
def gpu_mem_get(id=None):
    ""
    if not use_gpu: return GPUMemory(0, 0, 0)
    if id is None: id = torch.cuda.current_device()
    try:
        handle = pynvml.nvmlDeviceGetHandleByIndex(id)
        info = pynvml.nvmlDeviceGetMemoryInfo(handle)
        return GPUMemory(*(map(b2mb, [info.total, info.free, info.used])))
    except:
        return GPUMemory(0, 0, 0)
989880
def get_total_memory():
    """"""
    if platform.system() != "Linux":
        return None

    with open("/proc/meminfo", "r") as in_file:
        for line in in_file:
            info = line.split()
            if info[0] == "MemTotal:" and info[-1] == "kB":
                memory_mb = int(int(info[1]) / 1024)
                return memory_mb

    return None
203895
def total_physical_memory():
    '''
    
    '''
    if psutil.version_info < (0, 6, 0):
        msg = 'virtual_memory is only available in psutil 0.6.0 or greater'
        raise CommandExecutionError(msg)
    try:
        return psutil.virtual_memory().total
    except AttributeError:
        # TOTAL_PHYMEM is deprecated but with older psutil versions this is
        # needed as a fallback.
        return psutil.TOTAL_PHYMEM