/// <summary>
        /// 添加谱面到缓存区
        /// </summary>
        /// <param name="md5">谱面md5</param>
        /// <param name="beatmap">谱面</param>
        public unsafe void Add(string md5, CacheBeatmap beatmap)
        {
            MemoryStatusEx status = new MemoryStatusEx();

            status.Length = (uint)sizeof(MemoryStatusEx);
            Win32.Api.Win32Api.GlobalMemoryStatusEx(out status);
            if (Marshal.GetLastWin32Error() != 0)
            {
                OutputHelper.Output("[osuTools::BeatmapCache] Failed to query memory usage. Operation aborted.");
                return;
            }
            else
            {
                double memPercent = (double)status.AvailablePhysicalMemory / status.TotalPhysicalMemory;

                /*OutputHelper.Output($"[osuTools::BeatmapCache] Current available memory: {status.AvailablePhysicalMemory / Math.Pow(1024, 2):f2}MB " +
                 *                  $"({memPercent:p2}) Program used {(double)_currentProcess.WorkingSet64 / status.TotalPhysicalMemory:p2}");*/
                if (memPercent > 0.95)
                {
                    Enabled = false;
                    Clear();
                    GC.Collect();
                }
                else
                {
                    Enabled = true;
                }
            }
            if (Enabled)
            {
                _beatmaps.Add(md5, beatmap);
            }
        }
Example #2
0
        void UpdateGPU(out float load, out float mem)
        {
            HWmon.Update();

            float
                vramTotalGB = HWmon.GPUTotalMemory / 1024f,
                gpuMemLoad  = HWmon.GPUMemoryLoad,
                vramUsed    = vramTotalGB * (gpuMemLoad / 100f),
                vramFree    = vramTotalGB - vramUsed,
                gpuMemCtrl  = HWmon.GPUMemCtrlLoad,
                gpuLoad     = HWmon.GPULoad,
                gpuTemp     = HWmon.GPUTemperature,
                gpuFanRPM   = HWmon.GPUFanSpeed,
                gpuFanLoad  = HWmon.GPUFanLoad,
                gpuClock    = HWmon.GPUClock;

            Sensor_GPU_MEM.Chart.Add(gpuMemLoad);
            Sensor_GPU_MEM.Value.Text = $"{vramFree:N2} GiB free\n{gpuMemLoad:N1} % usage\n{gpuMemCtrl:N1} % Ctrl";

            Sensor_GPU_Load.Chart.Add(gpuLoad);
            Sensor_GPU_Load.Value.Text = $"{gpuLoad:N1} %\n{gpuTemp:N1} C\n{gpuClock:N0} MHz\n{gpuFanRPM:N0} RPM [{gpuFanLoad:N0}%]";

            load = gpuLoad / 10f;
            mem  = ((gpuMemLoad / 10f) - 7f).Min(0f) + (gpuMemCtrl / 10f);
        }
Example #3
0
        public static uint GetMemoryLoad()
        {
            if (_noGlobalMemoryStatusEx)
            {
                // In the absence of a measure of memory usage, act conservatively
                // and return a high value. Tweaking batch size configuration parameters
                // should help mitigate performance issues
                return(100);
            }

            try
            {
                var ms = new MemoryStatusEx();
                if (GlobalMemoryStatusEx(ms))
                {
                    return(ms.dwMemoryLoad);
                }
            }
            catch (System.EntryPointNotFoundException)
            {
                // Indicates we are on a Mono platform that does not currently support this native method
                _noGlobalMemoryStatusEx = true;
            }
            return(100);
        }
Example #4
0
        public static uint GetMemoryLoad()
        {
            if (_noGlobalMemoryStatusEx)
            {
                // In the absence of a measure of memory usage, act conservatively
                // and return a high value. Tweaking batch size configuration parameters
                // should help mitigate performance issues
                return 100;
            }

            try
            {
                var ms = new MemoryStatusEx();
                if (GlobalMemoryStatusEx(ms))
                {
                    return ms.dwMemoryLoad;
                }
            }
            catch (System.EntryPointNotFoundException)
            {
                // Indicates we are on a Mono platform that does not currently support this native method
                _noGlobalMemoryStatusEx = true;
            }
            return 100;
        }
Example #5
0
        private void Timer_Tick(object sender, EventArgs eventArgs)
        {
            MemoryStatusEx memoryInfo = new MemoryStatusEx();

            memoryInfo.dwLength = (uint)Marshal.SizeOf(memoryInfo);
            GlobalMemoryStatusEx(ref memoryInfo);
            UsedMem = $"{Math.Round((memoryInfo.ullTotalPhys - memoryInfo.ullAvailPhys) / (double)memoryInfo.ullTotalPhys * 100, 0)}%";
        }
Example #6
0
    public static long GetCommitted()
    {
        MemoryStatusEx mex = new MemoryStatusEx();

        mex.length = Marshal.SizeOf(mex);
        GlobalMemoryStatusEx(mex);
        return(mex.totalPageFile - mex.availPageFile);
    }
Example #7
0
 public static MemoryStatusEx GetMemoryStatus()
 {
     var res = new MemoryStatusEx();
     if (!GlobalMemoryStatusEx(res))
     {
         throw new Win32Exception();
     }
     return res;
 }
Example #8
0
 public static uint GetMemoryLoad()
 {
     var ms = new MemoryStatusEx();
     if (GlobalMemoryStatusEx(ms))
     {
         return ms.dwMemoryLoad;
     }
     return 100;
 }
Example #9
0
        public static uint GetAvailablePhysicalMemory()
        {
            var status = new MemoryStatusEx {
                Length = (uint)Marshal.SizeOf(typeof(MemoryStatusEx))
            };

            GlobalMemoryStatusEx(ref status);
            return((uint)(status.AvailablePhysicalMemory / (1024 * 1024)));
        }
 public override void Append(ErrorInfo errorInfo)
 {
     var memorystatusex = new MemoryStatusEx();
     if (NativeMethods.GlobalMemoryStatusEx(memorystatusex))
     {
         errorInfo.AddDetail(this.Name, "Total Memory", string.Format(CultureInfo.InvariantCulture, "{0} MB", memorystatusex.ullTotalPhys / (1024 * 1024)));
         errorInfo.AddDetail(this.Name, "Available Memory", string.Format(CultureInfo.InvariantCulture, "{0} MB", memorystatusex.ullAvailPhys / (1024 * 1024)));
     }
 }
Example #11
0
        private static ulong WindowsGetFreePhysicalMemory()
        {
            MemoryStatusEx memoryStatus = new MemoryStatusEx();

            memoryStatus.Length = 64;
            bool ok = NativeMethods.Kernel32.GlobalMemoryStatusEx(ref memoryStatus);

            return(memoryStatus.AvailPhys);
        }
        public static long GetTotalPhysicalMemory()
        {
            if (_memoryStatusEx == null)
            {
                _memoryStatusEx = new MemoryStatusEx();
                GlobalMemoryStatusEx(_memoryStatusEx);
            }

            return(_memoryStatusEx.ullTotalPhys);
        }
Example #13
0
        public static uint GetMemoryLoad()
        {
            var ms = new MemoryStatusEx();

            if (GlobalMemoryStatusEx(ms))
            {
                return(ms.dwMemoryLoad);
            }
            return(100);
        }
Example #14
0
        private static unsafe MemoryInfoResult GetMemoryInfoWindows()
        {
            // windows
            var memoryStatus = new MemoryStatusEx
            {
                dwLength = (uint)sizeof(MemoryStatusEx)
            };

            if (GlobalMemoryStatusEx(&memoryStatus) == false)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Failure when trying to read memory info from Windows, error code is: " + Marshal.GetLastWin32Error());
                }
                return(FailedResult);
            }

            // The amount of physical memory retrieved by the GetPhysicallyInstalledSystemMemory function
            // must be equal to or greater than the amount reported by the GlobalMemoryStatusEx function
            // if it is less, the SMBIOS data is malformed and the function fails with ERROR_INVALID_DATA.
            // Malformed SMBIOS data may indicate a problem with the user's computer.
            var fetchedInstalledMemory = GetPhysicallyInstalledSystemMemory(out var installedMemoryInKb);

            SetMemoryRecords((long)memoryStatus.ullAvailPhys);

            return(new MemoryInfoResult
            {
                TotalCommittableMemory = new Size((long)memoryStatus.ullTotalPageFile, SizeUnit.Bytes),
                CurrentCommitCharge = new Size((long)(memoryStatus.ullTotalPageFile - memoryStatus.ullAvailPageFile), SizeUnit.Bytes),
                AvailableMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes),
                AvailableWithoutTotalCleanMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes),
                SharedCleanMemory = Size.Zero,
                TotalPhysicalMemory = new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                InstalledMemory = fetchedInstalledMemory ?
                                  new Size(installedMemoryInKb, SizeUnit.Kilobytes) :
                                  new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                MemoryUsageRecords = new MemoryInfoResult.MemoryUsageLowHigh
                {
                    High = new MemoryInfoResult.MemoryUsageIntervals
                    {
                        LastOneMinute = new Size(HighLastOneMinute, SizeUnit.Bytes),
                        LastFiveMinutes = new Size(HighLastFiveMinutes, SizeUnit.Bytes),
                        SinceStartup = new Size(HighSinceStartup, SizeUnit.Bytes)
                    },
                    Low = new MemoryInfoResult.MemoryUsageIntervals
                    {
                        LastOneMinute = new Size(LowLastOneMinute, SizeUnit.Bytes),
                        LastFiveMinutes = new Size(LowLastFiveMinutes, SizeUnit.Bytes),
                        SinceStartup = new Size(LowSinceStartup, SizeUnit.Bytes)
                    }
                }
            });
        }
Example #15
0
        static SystemController()
        {
            Cpu    = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            Memory = new PerformanceCounter("Memory", "Available MBytes", string.Empty);

            var memStatus = new MemoryStatusEx();

            if (NativeMethods.GlobalMemoryStatusEx(memStatus))
            {
                TotalPhysicalMemory = memStatus.ullTotalPhys;
            }
        }
Example #16
0
        public MemoryStatusEx?GetMemoryStatusInfo()
        {
            var status = new MemoryStatusEx {
                Length = checked ((uint)Marshal.SizeOf(typeof(MemoryStatusEx)))
            };

            if (!Native.GlobalMemoryStatusEx(ref status))
            {
                return(null);
            }

            return(status);
        }
Example #17
0
        public int GetDiskFreeSpace(ref ulong freeBytesAvailable, ref ulong totalBytes,
                                    ref ulong totalFreeBytes, DokanFileInfo info)
        {
            MemoryStatusEx ms = new MemoryStatusEx();

            ms.dwLength = (uint)Marshal.SizeOf(ms);
            GlobalMemoryStatusEx(ref ms);
            totalBytes         = ms.ullTotalPageFile;
            freeBytesAvailable = ms.ullAvailPageFile;
            totalFreeBytes     = ms.ullAvailPageFile;

            return(0);
        }
Example #18
0
        public RamSensor(Process process)
        {
            Name = "RAM Load";

            counter = new PerformanceCounter("Process", "Working Set - Private", process.ProcessName);

            MemoryStatusEx status = new MemoryStatusEx
            {
                Length = checked ((uint)Marshal.SizeOf(typeof(MemoryStatusEx)))
            };

            TotalRam = GlobalMemoryStatusEx(status) ? (status.TotalPhys / (1024 * 1024)) : 1f;
        }
Example #19
0
        public static MemoryInfo Observe()
        {
            var memoryStatus = new MemoryStatusEx();

            if (GlobalMemoryStatusEx(memoryStatus))
            {
                return(new MemoryInfo(
                           total: (long)memoryStatus.ullTotalPhys,
                           available: (long)memoryStatus.ullAvailPhys
                           ));
            }

            throw new Exception("Error observing local memory");
        }
Example #20
0
        private static (ulong Total, ulong Available) GetMemoryStats()
        {
            MemoryStatusEx memStatus = new MemoryStatusEx();

            if (GlobalMemoryStatusEx(memStatus))
            {
                return(memStatus.TotalPhys, memStatus.AvailPhys);  // Bytes
            }
            else
            {
                Logger.Error?.Print(LogClass.Application, $"GlobalMemoryStatusEx failed. Error {Marshal.GetLastWin32Error():X}");
            }

            return(0, 0);
        }
Example #21
0
        public static MemoryInfo Observe()
        {
            var memoryStatus = new MemoryStatusEx();

            if (GlobalMemoryStatusEx(memoryStatus))
            {
                return new MemoryInfo {
                    Total = (long)memoryStatus.ullTotalPhys,
                    Available = (long)memoryStatus.ullAvailPhys
                };
            }


            throw new Exception("Could not observe local memory");
        }
Example #22
0
        public static MemoryInformation GetMemoryInformation()
        {
            var returnVal = new MemoryInformation();

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                // from http://stackoverflow.com/a/105109
                var memStatus = new MemoryStatusEx();
                if (GlobalMemoryStatusEx(memStatus))
                {
                    returnVal.TotalPhysicalMemory = memStatus.ullTotalPhys;
                    returnVal.TotalVirtualMemory  = memStatus.ullTotalVirtual;
                }
            }
            else
            {
                var meminfo = File.ReadAllText("/proc/meminfo");
                var match   = new Regex(@"MemTotal:\s+(\d+) kB").Match(meminfo);
                if (match.Success)
                {
                    returnVal.TotalPhysicalMemory = ulong.Parse(match.Groups[1].Value) * 1024;
                }

                ulong totalSwapMemory = 0;
                var   match2          = new Regex(@"SwapTotal:\s+(\d+) kB").Match(meminfo);
                if (match2.Success)
                {
                    totalSwapMemory = ulong.Parse(match2.Groups[1].Value) * 1024;
                }
                var availableMemory = returnVal.TotalPhysicalMemory + totalSwapMemory;
                if (Environment.Is64BitProcess)
                {
                    returnVal.TotalVirtualMemory = availableMemory;
                }
                else
                {
                    // Googling indicates that 32-bit Mono programs attempting to allocate more than
                    // about 1.4 GB start running into OutOfMemory errors.  So 2GB is probably the
                    // right virtual memory limit for 32-bit processes.
                    const ulong twoGB = 2147483648L;
                    returnVal.TotalVirtualMemory = availableMemory > twoGB ? twoGB : availableMemory;
                }
            }
            return(returnVal);
        }
        public static int GetMemoryLoad(this IMemoryInfo i)
        {
            MemoryStatusEx mse = new MemoryStatusEx();

            mse.dwLength = (uint)Marshal.SizeOf(mse);

            if (GlobalMemoryStatusEx(ref mse))
            {
                return((int)mse.dwMemoryLoad);
            }
            MemoryStatus ms = new MemoryStatus();

            if (GlobalMemoryStatus(ref ms))
            {
                return((int)ms.dwMemoryLoad);
            }
            return(-1);
        }
Example #24
0
        private static unsafe MemoryInfoResult GetMemoryInfoWindows(Process process, bool extended)
        {
            // windows
            var memoryStatus = new MemoryStatusEx
            {
                dwLength = (uint)sizeof(MemoryStatusEx)
            };

            if (GlobalMemoryStatusEx(&memoryStatus) == false)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Failure when trying to read memory info from Windows, error code is: " + Marshal.GetLastWin32Error());
                }
                return(FailedResult);
            }

            // The amount of physical memory retrieved by the GetPhysicallyInstalledSystemMemory function
            // must be equal to or greater than the amount reported by the GlobalMemoryStatusEx function
            // if it is less, the SMBIOS data is malformed and the function fails with ERROR_INVALID_DATA.
            // Malformed SMBIOS data may indicate a problem with the user's computer.
            var fetchedInstalledMemory = GetPhysicallyInstalledSystemMemory(out var installedMemoryInKb);

            var sharedCleanInBytes = GetSharedCleanInBytes(process);
            var availableMemoryForProcessingInBytes = (long)memoryStatus.ullAvailPhys + sharedCleanInBytes;

            SetMemoryRecords(availableMemoryForProcessingInBytes);

            return(new MemoryInfoResult
            {
                TotalCommittableMemory = new Size((long)memoryStatus.ullTotalPageFile, SizeUnit.Bytes),
                CurrentCommitCharge = new Size((long)(memoryStatus.ullTotalPageFile - memoryStatus.ullAvailPageFile), SizeUnit.Bytes),
                AvailableMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes),
                AvailableMemoryForProcessing = new Size(availableMemoryForProcessingInBytes, SizeUnit.Bytes),
                SharedCleanMemory = new Size(sharedCleanInBytes, SizeUnit.Bytes),
                TotalPhysicalMemory = new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                InstalledMemory = fetchedInstalledMemory ?
                                  new Size(installedMemoryInKb, SizeUnit.Kilobytes) :
                                  new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                WorkingSet = new Size(process?.WorkingSet64 ?? 0, SizeUnit.Bytes),
                IsExtended = extended,
                TotalSwapUsage = new Size(process?.PagedMemorySize64 ?? 0, SizeUnit.Bytes)
            });
        }
Example #25
0
        /// <summary>
        /// Determines the amount of RAM available to the operating system in total.
        /// </summary>
        /// <returns>Total RAM in MegaBytes</returns>
        private int GetRamInMegaBytes()
        {
            int result = 0;
            var mem    = new MemoryStatusEx();

            try
            {
                if (GlobalMemoryStatusEx(mem))
                {
                    result = Convert.ToInt32(mem.ullTotalPhys / 1048576);
                }
                else
                {
                    ServiceRegistration.Get <ILogger>().Warn("SQLiteDatabase: Error when trying to detect the total available RAM. Using minimum cache size for SQLiteDatabase.");
                }
            }
            catch (Exception)
            {
                ServiceRegistration.Get <ILogger>().Warn("SQLiteDatabase: Exception when trying to detect the total available RAM. Using minimum cache size for SQLiteDatabase.");
            }
            return(result);
        }
Example #26
0
 static extern bool GlobalMemoryStatusEx(ref MemoryStatusEx lpBuffer);
Example #27
0
 static extern bool GlobalMemoryStatusEx([In, Out] MemoryStatusEx buffer);
Example #28
0
        public static unsafe MemoryInfoResult GetMemoryInfo()
        {
            if (failedToGetAvailablePhysicalMemory)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Because of a previous error in getting available memory, we are now lying and saying we have 256MB free");
                }
                return(failedResult);
            }

            try
            {
                if (StorageEnvironmentOptions.RunningOnPosix)
                {
                    sysinfo_t info = new sysinfo_t();
                    if (Syscall.sysinfo(ref info) != 0)
                    {
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info("Failure when trying to read memory info from posix, error code was: " + Marshal.GetLastWin32Error());
                        }
                        return(failedResult);
                    }

                    return(new MemoryInfoResult
                    {
                        AvailableMemory = new Size((long)info.AvailableRam, SizeUnit.Bytes),
                        TotalPhysicalMemory = new Size((long)info.TotalRam, SizeUnit.Bytes),
                    });
                }



                var memoryStatus = new MemoryStatusEx
                {
                    dwLength = (uint)sizeof(MemoryStatusEx)
                };
                var result = GlobalMemoryStatusEx(&memoryStatus);
                if (result == false)
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info("Failure when trying to read memory info from Windows, error code is: " + Marshal.GetLastWin32Error());
                    }
                    return(failedResult);
                }

                return(new MemoryInfoResult
                {
                    AvailableMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes),
                    TotalPhysicalMemory = new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                });
            }
            catch (Exception e)
            {
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Error while trying to get available memory, will stop trying and report that there is 256MB free only from now on", e);
                }
                failedToGetAvailablePhysicalMemory = true;
                return(failedResult);
            }
        }
Example #29
0
        public int GetDiskFreeSpace(ref ulong freeBytesAvailable, ref ulong totalBytes,
            ref ulong totalFreeBytes, DokanFileInfo info)
        {
            MemoryStatusEx ms = new MemoryStatusEx();
            ms.dwLength = (uint)Marshal.SizeOf(ms);
            GlobalMemoryStatusEx(ref ms);
            totalBytes = ms.ullTotalPageFile;
            freeBytesAvailable = ms.ullAvailPageFile;
            totalFreeBytes = ms.ullAvailPageFile;

            return 0;
        }
Example #30
0
 private static extern void GlobalMemoryStatusEx(out MemoryStatusEx stat);
Example #31
0
 /// <summary>
 /// Determines the amount of RAM available to the operating system in total.
 /// </summary>
 /// <returns>Total RAM in MegaBytes</returns>
 private int GetRamInMegaBytes()
 {
   int result = 0;
   var mem = new MemoryStatusEx();
   try
   {
     if (GlobalMemoryStatusEx(mem))
       result = Convert.ToInt32(mem.ullTotalPhys / 1048576);
     else
       ServiceRegistration.Get<ILogger>().Warn("SQLiteDatabase: Error when trying to detect the total available RAM. Using minimum cache size for SQLiteDatabase.");
   }
   catch (Exception)
   {
     ServiceRegistration.Get<ILogger>().Warn("SQLiteDatabase: Exception when trying to detect the total available RAM. Using minimum cache size for SQLiteDatabase.");
   }
   return result;
 }
 public static bool GetMemoryStatusEx(this IMemoryInfo m, ref MemoryStatusEx mse)
 {
     mse.dwLength = (uint)Marshal.SizeOf(mse);
     return(GlobalMemoryStatusEx(ref mse));
 }
Example #33
0
 /// <summary>
 ///     returns the number of GB installed on the machine
 /// </summary>
 public static double TotalPhysicalMemoryGB()
 {
     if (Utilities.IsThisMono())
     {
         PerformanceCounter counter = new PerformanceCounter("Mono Memory", "Total Physical Memory");
         double physicalGB = (counter.RawValue / NumBytesInGB);
         return physicalGB;
     }
     MemoryStatusEx stat = new MemoryStatusEx();
     GlobalMemoryStatusEx(stat);
     double result = stat.TotalPhysical / NumBytesInGB;
     return result;
 }
Example #34
0
 internal static extern bool GlobalMemoryStatusEx(
     ref MemoryStatusEx buffer);
Example #35
0
#pragma warning disable AV1706 // Identifier contains an abbreviation or is too short
#pragma warning disable AV1562 // Do not declare a parameter as ref or out
        public static extern bool GlobalMemoryStatusEx(ref MemoryStatusEx meminfo);
Example #36
0
 private static extern bool GlobalMemoryStatusEx([In, Out] MemoryStatusEx lpBuffer);
Example #37
0
 public static extern bool GlobalMemoryStatusEx( MemoryStatusEx memStatus);
Example #38
0
 /// <summary>
 ///     returns the number of GB available on the machine
 /// </summary>
 public static double TotalPhysicalAvailableMemoryGB()
 {
     if (Utilities.IsThisMono())
     {
         UInt64 freeMemoryKB = 0;
         UInt64 cachedMemoryKB = 0;
         UInt64 bufferedMemoryKB = 0;
         try
         {
             // If we're on linux, go looking for memory info
             // in the meminfo file.
             // Hoping to see an entry that looks like
             //  MemFree:       1976408 kB
             //  Buffers:        348648 kB
             //  Cached:        4665328 kB
             // that specifies the available memory. There is certain
             // memory taken by the operating system (buffers, cache) that
             // can be made available if requested.
             StreamReader reader = new StreamReader("/proc/meminfo");
             string input = null;
             while ((input = reader.ReadLine()) != null)
             {
                 string[] splat = input.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                 if (splat.Length >= 2)
                 {
                     if (splat[0] == "MemFree:")
                     {
                         UInt64.TryParse(splat[1], out freeMemoryKB);
                     }
                     if (splat[0] == "Buffers:")
                     {
                         UInt64.TryParse(splat[1], out bufferedMemoryKB);
                     }
                     if (splat[0] == "Cached:")
                     {
                         UInt64.TryParse(splat[1], out cachedMemoryKB);
                     }
                 }
             }
             reader.Close();
         }
         catch (Exception e)
         {
             Console.WriteLine(e);
         }
         return (freeMemoryKB + cachedMemoryKB + bufferedMemoryKB) / NumKBInGB;
     }
     MemoryStatusEx stat = new MemoryStatusEx();
     GlobalMemoryStatusEx(stat);
     return stat.AvailablePhysical / NumBytesInGB;
 }
Example #39
0
 public static long GetCommitted()
 {
     MemoryStatusEx mex = new MemoryStatusEx();
     mex.length = Marshal.SizeOf(mex);
     GlobalMemoryStatusEx(mex);
     return mex.totalPageFile - mex.availPageFile;
 }
Example #40
0
 private static extern void GlobalMemoryStatusEx(out MemoryStatusEx stat);
Example #41
0
 private static extern bool GlobalMemoryStatusEx(ref MemoryStatusEx lpBuffer);
Example #42
0
        public static unsafe MemoryInfoResult GetMemoryInfo()
        {
            if (_failedToGetAvailablePhysicalMemory)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Because of a previous error in getting available memory, we are now lying and saying we have 256MB free");
                }
                return(FailedResult);
            }

            try
            {
                if (PlatformDetails.RunningOnPosix == false)
                {
                    // Windows
                    var memoryStatus = new MemoryStatusEx
                    {
                        dwLength = (uint)sizeof(MemoryStatusEx)
                    };
                    var result = GlobalMemoryStatusEx(&memoryStatus);
                    if (result == false)
                    {
                        if (Logger.IsInfoEnabled)
                        {
                            Logger.Info("Failure when trying to read memory info from Windows, error code is: " + Marshal.GetLastWin32Error());
                        }
                        return(FailedResult);
                    }

                    return(new MemoryInfoResult
                    {
                        AvailableMemory = new Size((long)memoryStatus.ullAvailPhys, SizeUnit.Bytes),
                        TotalPhysicalMemory = new Size((long)memoryStatus.ullTotalPhys, SizeUnit.Bytes),
                    });
                }

                // read both cgroup and sysinfo memory stats, and use the lowest if applicable
                var cgroupMemoryLimit = KernelVirtualFileSystemUtils.ReadNumberFromCgroupFile("/sys/fs/cgroup/memory/memory.limit_in_bytes");
                var cgroupMemoryUsage = KernelVirtualFileSystemUtils.ReadNumberFromCgroupFile("/sys/fs/cgroup/memory/memory.usage_in_bytes");

                ulong availableRamInBytes;
                ulong totalPhysicalMemoryInBytes;

                if (PlatformDetails.RunningOnMacOsx == false)
                {
                    // Linux
                    var info = new sysinfo_t();
                    if (Syscall.sysinfo(ref info) != 0)
                    {
                        if (Logger.IsInfoEnabled)
                        {
                            Logger.Info("Failure when trying to read memory info from posix, error code was: " + Marshal.GetLastWin32Error());
                        }
                        return(FailedResult);
                    }

                    availableRamInBytes        = info.AvailableRam;
                    totalPhysicalMemoryInBytes = info.TotalRam;
                }
                else
                {
                    // MacOS
                    var   mib            = new[] { (int)TopLevelIdentifiersMacOs.CTL_HW, (int)CtkHwIdentifiersMacOs.HW_MEMSIZE };
                    ulong physicalMemory = 0;
                    var   len            = sizeof(ulong);

                    if (Syscall.sysctl(mib, 2, &physicalMemory, &len, null, UIntPtr.Zero) != 0)
                    {
                        if (Logger.IsInfoEnabled)
                        {
                            Logger.Info("Failure when trying to read physical memory info from MacOS, error code was: " + Marshal.GetLastWin32Error());
                        }
                        return(FailedResult);
                    }

                    totalPhysicalMemoryInBytes = physicalMemory;

                    uint pageSize;
                    var  vmStats = new vm_statistics64();

                    var machPort = Syscall.mach_host_self();
                    var count    = sizeof(vm_statistics64) / sizeof(uint);

                    if (Syscall.host_page_size(machPort, &pageSize) != 0 ||
                        Syscall.host_statistics64(machPort, (int)FlavorMacOs.HOST_VM_INFO64, &vmStats, &count) != 0)
                    {
                        if (Logger.IsInfoEnabled)
                        {
                            Logger.Info("Failure when trying to get vm_stats from MacOS, error code was: " + Marshal.GetLastWin32Error());
                        }
                        return(FailedResult);
                    }

                    availableRamInBytes = vmStats.FreePagesCount * (ulong)pageSize;
                }

                Size availableRam, totalPhysicalMemory;
                if (cgroupMemoryLimit < (long)totalPhysicalMemoryInBytes)
                {
                    availableRam        = new Size(cgroupMemoryLimit - cgroupMemoryUsage, SizeUnit.Bytes);
                    totalPhysicalMemory = new Size(cgroupMemoryLimit, SizeUnit.Bytes);
                }
                else
                {
                    availableRam        = new Size((long)availableRamInBytes, SizeUnit.Bytes);
                    totalPhysicalMemory = new Size((long)totalPhysicalMemoryInBytes, SizeUnit.Bytes);
                }

                return(new MemoryInfoResult
                {
                    AvailableMemory = availableRam,
                    TotalPhysicalMemory = totalPhysicalMemory
                });
            }
            catch (Exception e)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Error while trying to get available memory, will stop trying and report that there is 256MB free only from now on", e);
                }
                _failedToGetAvailablePhysicalMemory = true;
                return(FailedResult);
            }
        }
Example #43
0
 internal static extern bool GlobalMemoryStatusEx(out MemoryStatusEx status);