Retrieves the amount of memory used by the process.

    Returns:
      int: amount of memory in bytes used by the process or None
          if not available.
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
907192
def get_memory_usage(self, variables = None):
        
        result = dict(
            total_nb_bytes = 0,
            by_variable = {}
            )
        for entity in self.populations.values():
            entity_memory_usage = entity.get_memory_usage(variables = variables)
            result['total_nb_bytes'] += entity_memory_usage['total_nb_bytes']
            result['by_variable'].update(entity_memory_usage['by_variable'])
        return result
519968
def collect(self):
        
        if ((os.access(self.PROC, os.R_OK) and
             self.config.get('force_psutil') != 'True')):
            file = open(self.PROC)
            data = file.read()
            file.close()

            memory_total = None
            memory_available = None
            for line in data.splitlines():
                try:
                    name, value, units = line.split()
                    name = name.rstrip(':')
                    value = int(value)

                    if ((name not in _KEY_MAPPING and
                         'detailed' not in self.config)):
                        continue

                    if name in 'MemTotal':
                        memory_total = value
                    elif name in 'MemAvailable':
                        memory_available = value

                    for unit in self.config['byte_unit']:
                        value = diamond.convertor.binary.convert(value=value,
                                                                 oldUnit=units,
                                                                 newUnit=unit)
                        self.publish(name, value, metric_type='GAUGE')

                        # TODO: We only support one unit node here. Fix it!
                        break

                except ValueError:
                    continue

            if memory_total is not None and memory_available is not None:
                memory_used = memory_total - memory_available
                memory_used_percent = Decimal(str(100.0 *
                                              memory_used /
                                              memory_total))
                self.publish('MemUsedPercentage',
                             round(memory_used_percent, 2),
                             metric_type='GAUGE')
            return True
        else:
            if not psutil:
                self.log.error('Unable to import psutil')
                self.log.error('No memory metrics retrieved')
                return None

            # psutil.phymem_usage() and psutil.virtmem_usage() are deprecated.
            if hasattr(psutil, "phymem_usage"):
                phymem_usage = psutil.phymem_usage()
                virtmem_usage = psutil.virtmem_usage()
            else:
                phymem_usage = psutil.virtual_memory()
                virtmem_usage = psutil.swap_memory()

            units = 'B'

            for unit in self.config['byte_unit']:
                memory_total = value = diamond.convertor.binary.convert(
                    value=phymem_usage.total, oldUnit=units, newUnit=unit)
                self.publish('MemTotal', value, metric_type='GAUGE')

                memory_available = value = diamond.convertor.binary.convert(
                    value=phymem_usage.available, oldUnit=units, newUnit=unit)
                self.publish('MemAvailable', value, metric_type='GAUGE')

                memory_used = memory_total - memory_available

                memory_used_percent = Decimal(str(100.0 *
                                              memory_used /
                                              memory_total))
                self.publish('MemUsedPercentage',
                             round(memory_used_percent, 2),
                             metric_type='GAUGE')

                value = diamond.convertor.binary.convert(
                    value=phymem_usage.free, oldUnit=units, newUnit=unit)
                self.publish('MemFree', value, metric_type='GAUGE')

                value = diamond.convertor.binary.convert(
                    value=virtmem_usage.total, oldUnit=units, newUnit=unit)
                self.publish('SwapTotal', value, metric_type='GAUGE')

                value = diamond.convertor.binary.convert(
                    value=virtmem_usage.free, oldUnit=units, newUnit=unit)
                self.publish('SwapFree', value, metric_type='GAUGE')

                # TODO: We only support one unit node here. Fix it!
                break

            return True
96173
def get_memory(self, start, size):
        
        LOG.debug('get_memory: %d bytes from %x', size, start)
        return get_memory(self.ida.idaapi, start, size,
                          default_byte=self.default_byte)
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]
558156
def get_cpu_usage(user=None, ignore_self=True):
    
    pid = os.getpid()
    cmd = "ps aux"
    output = getoutput(cmd)
    total = 0
    largest_process = 0
    largest_process_name = None
    for row in output.split('\n')[1:]:
        row = row.split()
        if row[1] == str(pid) and ignore_self:
            continue
        if user is None or user == row[0]:
            cpu = decimal.Decimal(row[2])
            if cpu > total:
                largest_process = cpu
                largest_process_name = ' '.join(row[10:len(row)])
            total += decimal.Decimal(row[2])
    return total, largest_process, largest_process_name
540318
def do_memory(self, arg):
        
        if arg:     # TODO: take min and max addresses
            raise CmdError("too many arguments")
        process = self.get_process_from_prefix()
        try:
            memoryMap       = process.get_memory_map()
            mappedFilenames = process.get_mapped_filenames()
            print('')
            print(CrashDump.dump_memory_map(memoryMap, mappedFilenames))
        except WindowsError:
            msg = "can't get memory information for process (%d)"
            raise CmdError(msg % process.get_pid())
496309
def size(self):
        
        tot = 0
        for p in self.__iter__(overPath=True):
            tot += os.path.getsize(p)
        return tot
708728
def get_size(self):
    
    if not self._is_open:
      raise IOError('Not opened.')

    if self._decoded_stream_size is None:
      self._decoded_stream_size = self._GetDecodedStreamSize()

    return self._decoded_stream_size
794421
public static String formatUsedMemory() {
		Runtime runtime = Runtime.getRuntime();
		long usedMemory = Math.max(0, runtime.totalMemory() - runtime.freeMemory());

		return MemoryUnitFormat.getMemoryUnitInstance().format(usedMemory);
	}
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
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}
858551
def get_data(self):
        
        data = []
        if self.counts:
            time_sec = self.duration
            memory_mb = self.mem / 1024. / 1024. if self.measuremem else 0
            data.append((self.operation, time_sec, memory_mb, self.counts))
        return numpy.array(data, perf_dt)
500233
def data(self):
        
        return self._buf[self.offset():self.offset() + self.size()]
101309
def process_info(pid=None):
    '''
    '''
    if psutil is None:  # pragma    nocover
        return {}
    pid = pid or os.getpid()
    try:
        p = psutil.Process(pid)
    # this fails on platforms which don't allow multiprocessing
    except psutil.NoSuchProcess:  # pragma    nocover
        return {}
    else:
        mem = p.memory_info()
        return {'memory': convert_bytes(mem.rss),
                'memory_virtual': convert_bytes(mem.vms),
                'cpu_percent': p.cpu_percent(),
                'nice': p.nice(),
                'num_threads': p.num_threads()}
1306915
def memory(self):
        
        if self._memory is not None:
            return self._memory
        elif self._config is not None:
            return self._config.defaultMemory
        else:
            raise AttributeError("Default value for 'memory' cannot be determined")
1005952
def pretty_memory_info():
    '''
    
    '''
    process = psutil.Process(os.getpid())
    return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))