References:
       http://stackoverflow.com/questions/141351/how-do-i-find-what-is-using-memory-in-a-python-process-in-a-production-system
776085
def memory_dump():
    
    import cPickle
    dump = open("memory.pickle", 'w')
    for obj in gc.get_objects():
        i = id(obj)
        size = sys.getsizeof(obj, 0)
        #    referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
        referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
        if hasattr(obj, '__class__'):
            cls = str(obj.__class__)
            cPickle.dump({'id': i, 'class': cls, 'size': size, 'referents': referents}, dump)
622753
def memory(self):
        
        class GpuMemoryInfo(Structure):
            _fields_ = [
                ('total', c_ulonglong),
                ('free', c_ulonglong),
                ('used', c_ulonglong),
            ]

        c_memory = GpuMemoryInfo()
        _check_return(_NVML.get_function(
            "nvmlDeviceGetMemoryInfo")(self.hnd, byref(c_memory)))
        return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used}
1183032
def _AddExtractionProcessStatusTableRow(self, process_status, table_view):
    
    used_memory = self._FormatSizeInUnitsOf1024(process_status.used_memory)

    sources = ''
    if (process_status.number_of_produced_sources is not None and
        process_status.number_of_produced_sources_delta is not None):
      sources = '{0:d} ({1:d})'.format(
          process_status.number_of_produced_sources,
          process_status.number_of_produced_sources_delta)

    events = ''
    if (process_status.number_of_produced_events is not None and
        process_status.number_of_produced_events_delta is not None):
      events = '{0:d} ({1:d})'.format(
          process_status.number_of_produced_events,
          process_status.number_of_produced_events_delta)

    # TODO: shorten display name to fit in 80 chars and show the filename.

    table_view.AddRow([
        process_status.identifier, process_status.pid, process_status.status,
        used_memory, sources, events, process_status.display_name])
1190056
def get_memory_info(self) -> str:
        ''''''
        output, _ = self._execute(
            '-s', self.device_sn, 'shell', 'cat', '/proc/meminfo')
        return output
620260
def peak_memory_usage():
    """"""
    if sys.platform.startswith('win'):
        p = psutil.Process()
        return p.memory_info().peak_wset / 1024 / 1024

    mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    factor_mb = 1 / 1024
    if sys.platform == 'darwin':
        factor_mb = 1 / (1024 * 1024)
    return mem * factor_mb
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
207092
def get_host_usage(self):
        
        import psutil
        process_names = [proc.name for proc in psutil.process_iter()]
        cpu_pct = psutil.cpu_percent(interval=1)
        mem = psutil.virtual_memory()
        return str(cpu_pct), str(len(process_names)), str(mem.available), str(mem.total)
813718
def get_memory(self, note=None):
		""""""
		shutit = self.shutit
		shutit.handle_note(note)
		if self.current_environment.distro == 'osx':
			memavail = self.send_and_get_output("""command vm_stat | grep ^Pages.free: | awk '{print $3}' | tr -d '.'""",
			                                    timeout=3,
			                                    echo=False)
			memavail = int(memavail)
			memavail *= 4
		else:
			memavail = self.send_and_get_output("""command cat /proc/meminfo  | grep MemAvailable | awk '{print $2}'""",
			                                    timeout=3,
			                                    echo=False)
			if memavail == '':
				memavail = self.send_and_get_output("""command free | grep buffers.cache | awk '{print $3}'""",
				                                    timeout=3,
				                                    echo=False)
			memavail = int(memavail)
		shutit.handle_note_after(note=note)
		return memavail
1313075
def _memory_usage(self, pid='self', category="hwm", container=None):
        
        if container:
            # TODO: Put some debug output here with switch to Logger
            # since this is relatively untested.
            cmd = "docker stats " + container + " --format '{{.MemUsage}}' --no-stream"
            mem_use_str = subprocess.check_output(cmd, shell=True)
            mem_use = mem_use_str.split("/")[0].split()
            
            mem_num = re.findall('[\d\.]+', mem_use_str.split("/")[0])[0]
            mem_scale = re.findall('[A-Za-z]+', mem_use_str.split("/")[0])[0]

            #print(mem_use_str, mem_num, mem_scale)
            mem_num = float(mem_num)
            if mem_scale == "GiB":
                return mem_num * 1e6
            elif mem_scale == "MiB":
                return mem_num * 1e3
            elif mem_scale == "KiB":
                return mem_num
            else:
                # What type is this?
                return 0

        # Thanks Martin Geisler:
        status = None
        result = {'peak': 0, 'rss': 0, 'hwm': 0}
        
        try:
            # This will only work on systems with a /proc file system
            # (like Linux).
            # status = open('/proc/self/status')
            proc_spot = '/proc/%s/status' % pid
            status = open(proc_spot)
            for line in status:
                parts = line.split()
                key = parts[0][2:-1].lower()
                if key in result:
                    result[key] = int(parts[1])
        except:
            return 0

        finally:
            if status is not None:
                status.close()
        # print(result[category])
        return result[category]
1112169
private long getMemoryUsage() {
    long totalPageSize = 0;
    for (MemoryBlock page : allocatedPages) {
      totalPageSize += page.size();
    }
    return ((inMemSorter == null) ? 0 : inMemSorter.getMemoryUsage()) + totalPageSize;
  }
617109
def cpu_and_memory(programs, items):
    
    assert len(items) > 0, "Finding job resources but no items to process"
    config = items[0]["config"]
    all_cores = []
    all_memory = []
    algs = [config_utils.get_algorithm_config(x) for x in items]
    progs = _get_resource_programs(programs, algs)
    # Calculate cores
    for prog in progs:
        resources = config_utils.get_resources(prog, config)
        all_cores.append(resources.get("cores", 1))
    if len(all_cores) == 0:
        all_cores.append(1)
    cores_per_job = max(all_cores)
    # Calculate memory. Use 1Gb memory usage per core as min baseline if not specified
    for prog in progs:
        resources = config_utils.get_resources(prog, config)
        memory = _get_prog_memory(resources, cores_per_job)
        if memory:
            all_memory.append(memory)
    if len(all_memory) == 0:
        all_memory.append(1)
    memory_per_core = max(all_memory)
    return cores_per_job, memory_per_core
1045476
def _is_memory_usage_qualified(self):
        
        def f(l):
            return 'mixed' in l or 'string' in l or 'unicode' in l
        return any(f(l) for l in self._inferred_type_levels)
1157378
private function _memory()
    {
        if (CommonFunctions::executeProgram('sysinfo', '-mem', $bufr, PSI_DEBUG)) {
            if (preg_match("/(.*)bytes free\s+\(used\/max\s+(.*)\s+\/\s+(.*)\)\s*\n\s+\(cached\s+(.*)\)/", $bufr, $ar_buf)) {
                $this->sys->setMemTotal($ar_buf[3]);
                $this->sys->setMemFree($ar_buf[1]);
                $this->sys->setMemCache($ar_buf[4]);
                $this->sys->setMemUsed($ar_buf[2]);
            }
        }
        if (CommonFunctions::executeProgram('vmstat', '', $bufr, PSI_DEBUG)) {
            if (preg_match("/max swap space:\s+(.*)\nfree swap space:\s+(.*)\n/", $bufr, $ar_buf)) {
                if ($ar_buf[1]>0) {
                    $dev = new DiskDevice();
                    $dev->setMountPoint("/boot/common/var/swap");
                    $dev->setName("SWAP");
                    $dev->setTotal($ar_buf[1]);
                    $dev->setFree($ar_buf[2]);
                    $dev->setUSed($ar_buf[1]-$ar_buf[2]);
                    $this->sys->setSwapDevices($dev);
                }
            }
        }
    }
41776
def usage(self):
        ''''''
        retval, stderr, stdout = _pysam_dispatch(
            self.collection,
            self.dispatch,
            is_usage=True,
            catch_stdout=True)
        # some tools write usage to stderr, such as mpileup
        if stderr:
            return stderr
        else:
            return stdout
638233
def total_memory(self, image='ubuntu'):
        ''''''
        try:
            ret = subprocess.check_output(
                f'''docker run -t {image} cat /proc/meminfo  | grep MemTotal''',
                shell=True,
                stdin=subprocess.DEVNULL)
            # ret: MemTotal:       30208916 kB
            self.tot_mem = int(ret.split()[1])
        except Exception:
            # some system does not have cat or grep
            self.tot_mem = None
        return self.tot_mem
210769
def SampleMemoryUsage(self, parser_name):
    
    if self._memory_profiler:
      used_memory = self._process_information.GetUsedMemory() or 0
      self._memory_profiler.Sample(parser_name, used_memory)
1288135
def current_memory_usage():
    
    import psutil
    proc = psutil.Process(os.getpid())
    #meminfo = proc.get_memory_info()
    meminfo = proc.memory_info()
    rss = meminfo[0]  # Resident Set Size / Mem Usage
    vms = meminfo[1]  # Virtual Memory Size / VM Size  # NOQA
    return rss