Return physical memory usage (float)
    Requires the cross-platform psutil (>=v0.3) library
    (https://github.com/giampaolo/psutil)
542539
def psutil_phymem_usage():
    
    import psutil
    # This is needed to avoid a deprecation warning error with
    # newer psutil versions
    try:
        percent = psutil.virtual_memory().percent
    except:
        percent = psutil.phymem_usage().percent
    return percent
654829
private Long getCpuTime() {
        if (bean instanceof com.sun.management.OperatingSystemMXBean) { //NOSONAR
            return ((com.sun.management.OperatingSystemMXBean) bean).getProcessCpuTime();  //NOSONAR
        } else {
            return -1L;
        }
    }
445948
def _memory_usage_ps():
    
    out = subprocess.Popen(
        ['ps', 'v', '-p', str(os.getpid())],
        stdout=subprocess.PIPE).communicate()[0].split(b'\n')
    vsz_index = out[0].split().index(b'RSS')
    mem = float(out[1].split()[vsz_index]) / 1024
    return mem
1230550
def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
    
    total_mem = "%.2f" % (cores * mem_per_core + system_memory)
    if "cores" not in sysinfo:
        return cores, total_mem, 1.0

    total_mem = min(float(total_mem), float(sysinfo["memory"]) - system_memory)
    cores = min(cores, int(sysinfo["cores"]))
    mem_cores = int(math.floor(float(total_mem) / mem_per_core))  # cores based on available memory
    if mem_cores < 1:
        out_cores = 1
    elif mem_cores < cores:
        out_cores = mem_cores
    else:
        out_cores = cores
    mem_pct = float(out_cores) / float(cores)
    return out_cores, total_mem, mem_pct
910569
def get_meminfo(opts):
    ''' 
    '''
    meminfo = MemInfo()
    outunit = opts.outunit
    mstat = get_mem_info()  # from winstats
    pinf = get_perf_info()
    try:
        pgpcnt = get_perf_data(r'\Paging File(_Total)\% Usage',
                                'double')[0] / 100
    except WindowsError:
        pgpcnt = 0

    totl = mstat.TotalPhys
    meminfo.memtotal = totl / float(outunit)
    used = totl * mstat.MemoryLoad / 100.0  # percent, more reliable
    meminfo.used = used / float(outunit)
    left = totl - used

    # Cached
    cache = pinf.SystemCacheBytes
    if cache > left and version >= win7ver:
        # Win7 RTM bug :/ this cache number is bogus
        free = get_perf_data(r'\Memory\Free & Zero Page List Bytes', 'long')[0]
        cache = left - free
        meminfo.memfree = free / float(outunit)
    else:
        meminfo.memfree = (totl - used - cache) / float(outunit)
    meminfo.buffers = 0

    meminfo.cached = cache / float(outunit)

    # SWAP  these numbers are actually commit charge, not swap; fix
    #       should not contain RAM :/
    swpt = abs(mstat.TotalPageFile - totl)
    # these nums aren't quite right either, use perfmon instead :/
    swpu = swpt * pgpcnt
    swpf = swpt - swpu

    meminfo.swaptotal = swpt / float(outunit)
    meminfo.swapfree = swpf / float(outunit)
    meminfo.swapused = swpu / float(outunit)
    meminfo.swapcached = 0  # A linux stat for compat

    if opts.debug:
        import locale
        fmt = lambda val: locale.format('%d', val, True)
        print()
        print('TotalPhys:', fmt(totl))
        print('AvailPhys:', fmt(mstat.AvailPhys))
        print('MemoryLoad:', fmt(mstat.MemoryLoad))
        print()
        print('used:', fmt(used))
        print('left:', fmt(left))
        if 'free' in locals():
            print('PDH Free:', fmt(free))
        print('SystemCacheBytes:', fmt(pinf.SystemCacheBytes))
        print()
        print('TotalPageFile:', fmt(mstat.TotalPageFile))
        print('AvailPageFile:', fmt(mstat.AvailPageFile))
        print('TotalPageFile fixed:', fmt(swpt))
        print('AvailPageFile fixed:', fmt(swpf))

    return meminfo
611501
def memoryCheck(vms_max_kb):
    
    safety_factor = 1.2
    vms_max = vms_max_kb
    vms_gigs = vms_max / 1024 ** 2
    buffer = safety_factor * vms_max
    buffer_gigs = buffer / 1024 ** 2
    vm = psutil.virtual_memory()
    free_gigs = vm.available / 1024 ** 2
    if vm.available < buffer:
        raise MemoryError('Running this requires quite a bit of memory ~ '
                          f'{vms_gigs:.2f}, you have {free_gigs:.2f} of the '
                          f'{buffer_gigs:.2f} needed')
586244
def log_memory(log, pref=None, lvl=logging.DEBUG, raise_flag=True):
    
    import os
    import sys
    cyc_str = ""
    KB = 1024.0
    if pref is not None:
        cyc_str += "{}: ".format(pref)

    # Linux returns units in Bytes; OSX in kilobytes
    UNIT = KB*KB if sys.platform == 'darwin' else KB

    good = False
    # Use the `resource` module to check the maximum memory usage of this process
    try:
        import resource
        max_self = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        max_child = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
        _str = "RSS Max Self: {:7.2f} [MB], Child: {:7.2f} [MB]".format(
            max_self/UNIT, max_child/UNIT)
        cyc_str += _str
    except Exception as err:
        log.log(lvl, "resource.getrusage failed.  '{}'".format(str(err)))
        if raise_flag:
            raise
    else:
        good = True

    # Use the `psutil` module to check the current memory/cpu usage of this process
    try:
        import psutil
        process = psutil.Process(os.getpid())
        rss = process.memory_info().rss
        cpu_perc = process.cpu_percent()
        mem_perc = process.memory_percent()
        num_thr = process.num_threads()
        _str = "; RSS: {:7.2f} [MB], {:7.2f}%; Threads: {:3d}, CPU: {:7.2f}%".format(
            rss/UNIT, mem_perc, num_thr, cpu_perc)
        cyc_str += _str
    except Exception as err:
        log.log(lvl, "psutil.Process failed.  '{}'".format(str(err)))
        if raise_flag:
            raise
    else:
        good = True

    if good:
        log.log(lvl, cyc_str)

    return
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
122128
public static double getUsedMemory() {
    	Runtime rt = Runtime.getRuntime();
    	
    	long memLong = rt.totalMemory() - rt.freeMemory();
    	double memDouble = memLong / (1024.0 * 1024.0);
    	memDouble = Math.round(memDouble * 100) / 100.0;
    	return memDouble;
    }
782012
def get_free_memory():
    
    if 'win32' in sys.platform:
        # windows
        return get_free_memory_win()
    elif 'linux' in sys.platform:
        # linux
        return get_free_memory_linux()
    elif 'darwin' in sys.platform:
        # mac
        return get_free_memory_osx()
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
1132821
def memory_usage(method):
  """"""
  def wrapper(*args, **kwargs):
    logging.info('Memory before method %s is %s.',
                 method.__name__, runtime.memory_usage().current())
    result = method(*args, **kwargs)
    logging.info('Memory after method %s is %s',
                 method.__name__, runtime.memory_usage().current())
    return result
  return wrapper
678164
def num_unused_cpus(thresh=10):
    
    import psutil
    cpu_usage = psutil.cpu_percent(percpu=True)
    return sum([p < thresh for p in cpu_usage])
7844
def GetUsedMemory(self):
    
    try:
      memory_info = self._process.memory_info()
    except psutil.NoSuchProcess:
      return None

    # Psutil will return different memory information depending on what is
    # available in that platform.
    memory_data = getattr(memory_info, 'data', 0)
    memory_shared = getattr(memory_info, 'shared', 0)

    return memory_data + memory_shared
505133
def peak_memory_mb() -> float:
    
    if resource is None or sys.platform not in ('linux', 'darwin'):
        return 0.0

    # TODO(joelgrus): For whatever, our pinned version 0.521 of mypy does not like
    # next line, but later versions (e.g. 0.530) are fine with it. Once we get that
    # figured out, remove the type: ignore.
    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss  # type: ignore

    if sys.platform == 'darwin':
        # On OSX the result is in bytes.
        return peak / 1_000_000

    else:
        # On Linux the result is in kilobytes.
        return peak / 1_000
1141362
public static long getTotalPhysicalMemory() {
   long memory = -1;
   try {
     MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
     Object attribute = mBeanServer.getAttribute(new ObjectName("java.lang","type","OperatingSystem"), "TotalPhysicalMemorySize");
     return (Long) attribute;
   } catch (Throwable e) { e.printStackTrace(); }
   return memory;
 }
262315
private static function getMemoryUsage() {

        $memory = memory_get_peak_usage();
        $floor = floor((strlen($memory) - 1) / 3);
        return sprintf("%.2f", $memory/pow(1024, $floor)).' '.@'BKMGTPEZY'[$floor].'B';
    }