Return current free memory on the machine for windows.

    Warning : this script is really not robust
    Return in MB unit
495847
def get_free_memory_win():
    
    stat = MEMORYSTATUSEX()
    ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
    return int(stat.ullAvailPhys / 1024 / 1024)
222447
def get_free_memory_osx():
    
    try:
        p = Popen('echo -e "\n$(top -l 1 | awk \'/PhysMem/\';)\n"',
                  shell=True, stdout=PIPE, encoding='utf8')
        stdout_string = p.communicate()[0].split('\n')[1]
        # e.g. output (its a single line) OSX 10.9 Mavericks
        # PhysMem: 6854M used (994M wired), 1332M unused.
        # output on Mountain lion
        # PhysMem: 1491M wired, 3032M active, 1933M inactive,
        # 6456M used, 1735M free.
    except OSError:
        raise OSError
    platform_version = platform.mac_ver()[0]
    # Might get '10.9.1' so strop off the last no
    parts = platform_version.split('.')
    platform_version = parts[0] + parts[1]
    # We make version a int by concatenating the two parts
    # so that we can successfully determine that 10.10 (release version)
    # is greater than e.g. 10.8 (release version)
    # 1010 vs 108
    platform_version = int(platform_version)

    if platform_version > 108:
        stdout_list = stdout_string.split(',')
        unused = stdout_list[1].replace('M unused', '').replace(' ', '')
        unused = unused.replace('.', '')
        return int(unused)
    else:
        stdout_list = stdout_string.split(',')
        inactive = stdout_list[2].replace('M inactive', '').replace(' ', '')
        free = stdout_list[4].replace('M free.', '').replace(' ', '')
        return int(inactive) + int(free)
1283744
def memory_usage(self, string=False):
        
        if string:
            n = getsizeof(self)
            return ' '.join((str(s) for s in convert_bytes(n)))
        return self.info()['size']
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
1322050
def get_memory_size(self):
        """"""
        n = sys.getsizeof(self)
        n += sys.getsizeof(self.padding)
        n += total_size(self.start_addr)
        n += total_size(self._buf)
        n += sys.getsizeof(self._offset)
        return n
374411
protected static function _getMemory()
    {
        if (function_exists('memory_get_usage')) {
            return memory_get_usage();
        } else {
            $output = array();
            $pid    = getmypid();

            if (substr(PHP_OS, 0, 3) == 'WIN') {
                @exec('tasklist /FI "PID eq ' . $pid . '" /FO LIST', $output);
                if (!isset($output[5])) {
                    $output[5] = null;
                }
                return (int)substr($output[5], strpos($output[5], ':') + 1);
            } else {
                @exec("ps -o rss -p $pid", $output);
                return $output[1] * 1024;
            }
        }
    }
414613
private static long getSizeOfFreeMemory() {
		float fractionToUse = GlobalConfiguration.getFloat(
			ConfigConstants.TASK_MANAGER_MEMORY_FRACTION_KEY, ConfigConstants.DEFAULT_MEMORY_MANAGER_MEMORY_FRACTION);
		
		Runtime r = Runtime.getRuntime();
		long max = r.maxMemory();
		long total = r.totalMemory();
		long free = r.freeMemory();
		
		long available = max - total + free;
		return (long) (fractionToUse * available);
	}
806169
def free(self):
        
        # Free the memory
        self._machine_controller.sdram_free(self._start_address,
                                            self._x, self._y)

        # Mark as freed
        self._freed = True
648721
def get_obj_store_free_space_bytes():
    """"""
    obj_store_path = django.conf.settings.OBJECT_STORE_PATH
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(
            ctypes.c_wchar_p(obj_store_path), None, None, ctypes.pointer(free_bytes)
        )
        return free_bytes.value
    else:
        return os.statvfs(obj_store_path).f_bfree * os.statvfs(obj_store_path).f_frsize
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
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
158696
def memory_usage_psutil():
    
    process = psutil.Process(os.getpid())
    mem = process.memory_info()[0] / float(2 ** 20)
    mem_vms = process.memory_info()[1] / float(2 ** 20)
    return mem, mem_vms
148533
def memory():
    

    mem_info = {}

    if platform.linux_distribution()[0]:
        with open('/proc/meminfo') as file:
            c = 0
            for line in file:
                lst = line.split()
                if str(lst[0]) == 'MemTotal:':
                    mem_info['total'] = int(lst[1])
                elif str(lst[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                    c += int(lst[1])
            mem_info['free'] = c
            mem_info['used'] = (mem_info['total']) - c
    elif platform.mac_ver()[0]:
        ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
        vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

        # Iterate processes
        process_lines = ps.split('\n')
        sep = re.compile('[\s]+')
        rss_total = 0  # kB
        for row in range(1, len(process_lines)):
            row_text = process_lines[row].strip()
            row_elements = sep.split(row_text)
            try:
                rss = float(row_elements[0]) * 1024
            except:
                rss = 0  # ignore...
            rss_total += rss

        # Process vm_stat
        vm_lines = vm.split('\n')
        sep = re.compile(':[\s]+')
        vm_stats = {}
        for row in range(1, len(vm_lines) - 2):
            row_text = vm_lines[row].strip()
            row_elements = sep.split(row_text)
            vm_stats[(row_elements[0])] = int(row_elements[1].strip('\.')) * 4096

        mem_info['total'] = rss_total
        mem_info['used'] = vm_stats["Pages active"]
        mem_info['free'] = vm_stats["Pages free"]
    else:
        raise('Unsupported Operating System.\n')
        exit(1)

    return mem_info
342474
def get_data(self, size=None, addr=None):
        '''
        
        '''
        # readback memory offset
        if addr is None:
            addr = self._mem_bytes

        if size and self._mem_bytes < size:
            raise ValueError('Size is too big')

        if size is None:
            return self._intf.read(self._conf['base_addr'] + self._spi_mem_offset + addr, self._mem_bytes)
        else:
            return self._intf.read(self._conf['base_addr'] + self._spi_mem_offset + addr, size)
673989
def free_memory(self):
        """"""
        self.main.free_memory()
        QTimer.singleShot(self.INITIAL_FREE_MEMORY_TIME_TRIGGER,
                          lambda: self.main.free_memory())
        QTimer.singleShot(self.SECONDARY_FREE_MEMORY_TIME_TRIGGER,
                          lambda: self.main.free_memory())
20327
def get_free_mb(folder):
    
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value/1024/1024
    else:
        st = os.statvfs(folder)
        return st.f_bavail * st.f_frsize/1024/1024
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