Return current free memory on the machine for linux.

    Warning : this script is really not robust
    Return in MB unit
162483
def get_free_memory_linux():
    
    try:
        p = Popen('free -m', shell=True, stdout=PIPE, encoding='utf8')
        stdout_string = p.communicate()[0].split('\n')[2]
    except OSError:
        raise OSError
    stdout_list = stdout_string.split(' ')
    stdout_list = [x for x in stdout_list if x != '']
    return int(stdout_list[3])
467396
public static int getMemoryInUse() {
    Runtime runtime = Runtime.getRuntime();
    long mb = 1024 * 1024;
    long total = runtime.totalMemory();
    long free = runtime.freeMemory();
    return (int) ((total - free) / mb);
  }
814285
@SuppressWarnings("resource")
	private static long getSizeOfPhysicalMemoryForLinux() {
		BufferedReader lineReader = null;
		try {
			lineReader = new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH));

			String line = null;
			while ((line = lineReader.readLine()) != null) {
				Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);
				if (matcher.matches()) {
					String totalMemory = matcher.group(1);
					return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte
				}
			}
			
			// expected line did not come
			LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo'. Unexpected format.");
			return -1;
		}
		catch (NumberFormatException e) {
			LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo'. Unexpected format.");
			return -1;
		}
		catch (IOException e) {
			LOG.error("Cannot determine the size of the physical memory using '/proc/meminfo': " + e.getMessage(), e);
			return -1;
		}
		finally {
			// Make sure we always close the file handle
			try {
				if (lineReader != null) {
					lineReader.close();
				}
			} catch (Throwable t) {}
		}
	}
351730
def cudaMemGetInfo():
    

    free = ctypes.c_size_t()
    total = ctypes.c_size_t()
    status = _libcudart.cudaMemGetInfo(ctypes.byref(free),
                                       ctypes.byref(total))
    cudaCheckStatus(status)
    return free.value, total.value
59504
def get_memory_expr(self, address, size, mode="post"):
        
        mem = self.get_memory(mode)

        return smtfunction.concat(8, *reversed([mem[address + i] for i in range(size)]))
894306
def read_memory(self):
        
        if self.mem_empty == True:
            if self.mem_idx == 0:
                m_x = np.zeros(self.n)
                m_d = 0
            else:
                m_x = np.mean(self.mem_x[:self.mem_idx+1], axis=0)
                m_d = np.mean(self.mem_d[:self.mem_idx])
        else:
            m_x = np.mean(self.mem_x, axis=0)
            m_d = np.mean(np.delete(self.mem_d, self.mem_idx))
        self.mem_idx += 1
        if self.mem_idx > len(self.mem_x)-1:
            self.mem_idx = 0
            self.mem_empty = False
        return m_d, m_x
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
1213201
def get_mem(device_handle):
    """"""
    try:
        memory_info = pynvml.nvmlDeviceGetMemoryInfo(device_handle)
        return memory_info.used * 100.0 / memory_info.total
    except pynvml.NVMLError:
        return None
110218
def GetMemBalloonedMB(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetMemBalloonedMB(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
567205
private static long getSizeOfPhysicalMemory() {
		switch (OperatingSystem.getCurrentOperatingSystem()) {
			case LINUX:
				return getSizeOfPhysicalMemoryForLinux();
				
			case WINDOWS:
				return getSizeOfPhysicalMemoryForWindows();
				
			case MAC_OS:
				return getSizeOfPhysicalMemoryForMac();
				
			case FREE_BSD:
				return getSizeOfPhysicalMemoryForFreeBSD();
				
			case UNKNOWN:
				LOG.error("Cannot determine size of physical memory for unknown operating system");
				return -1;
				
			default:
				LOG.error("Unrecognized OS");
				return -1;
		}
	}
478641
def GetMemActiveMB(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
402112
function getMemory(size) {
  if (!staticSealed) return staticAlloc(size);
  if (!runtimeInitialized) return dynamicAlloc(size);
  return _malloc(size);
}
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
1233291
def sys_mem_limit(self):
        """"""
        if platform.machine() in ['armv7l']:
            _mem_limit = self.human_to_bytes('2700M')  # experimentally determined
        else:
            # Limit for x86 based 32bit systems
            _mem_limit = self.human_to_bytes('4G')

        return _mem_limit
1169725
def check_available_ram(self, requested_ram):
        

        available_ram = int(psutil.virtual_memory().available / (1024 * 1024))
        percentage_left = psutil.virtual_memory().percent
        if requested_ram > available_ram:
            message = '"{}" requires {}MB of RAM to run but there is only {}MB - {}% of RAM left on "{}"'.format(self.name,
                                                                                                                 requested_ram,
                                                                                                                 available_ram,
                                                                                                                 percentage_left,
                                                                                                                 platform.node())
            self.project.emit("log.warning", {"message": message})
1112223
def get_shared_memory_bytes():
    
    # Make sure this is only called on Linux.
    assert sys.platform == "linux" or sys.platform == "linux2"

    shm_fd = os.open("/dev/shm", os.O_RDONLY)
    try:
        shm_fs_stats = os.fstatvfs(shm_fd)
        # The value shm_fs_stats.f_bsize is the block size and the
        # value shm_fs_stats.f_bavail is the number of available
        # blocks.
        shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail
    finally:
        os.close(shm_fd)

    return shm_avail
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