public static MachineResources GetMachineResources()
        {
            using (var currentProcess = Process.GetCurrentProcess())
            {
                var workingSet = PlatformDetails.RunningOnLinux == false
                        ? currentProcess.WorkingSet64
                        : MemoryInformation.GetRssMemoryUsage(currentProcess.Id);

                var memoryInfoResult = MemoryInformation.GetMemoryInfo();
                var cpuInfo          = CpuUsage.Calculate();

                var machineResources = new MachineResources
                {
                    TotalMemory        = memoryInfoResult.TotalPhysicalMemory.GetValue(SizeUnit.Bytes),
                    SystemCommitLimit  = memoryInfoResult.TotalCommittableMemory.GetValue(SizeUnit.Bytes),
                    CommitedMemory     = memoryInfoResult.CurrentCommitCharge.GetValue(SizeUnit.Bytes),
                    ProcessMemoryUsage = workingSet,
                    IsProcessMemoryRss = PlatformDetails.RunningOnPosix,
                    MachineCpuUsage    = cpuInfo.MachineCpuUsage,
                    ProcessCpuUsage    = Math.Min(cpuInfo.MachineCpuUsage, cpuInfo.ProcessCpuUsage) // min as sometimes +-1% due to time sampling
                };

                return(machineResources);
            }
        }
        public static MachineResources GetMachineResources(SmapsReader smapsReader)
        {
            using (var currentProcess = Process.GetCurrentProcess())
            {
                var memInfo     = MemoryInformation.GetMemoryInfo(smapsReader);
                var isLowMemory = LowMemoryNotification.Instance.IsLowMemory(memInfo);
                var workingSet  = PlatformDetails.RunningOnLinux
                    ? MemoryInformation.GetRssMemoryUsage(currentProcess.Id) - memInfo.AvailableWithoutTotalCleanMemory.GetValue(SizeUnit.Bytes)
                    : currentProcess.WorkingSet64;

                var cpuInfo = CpuUsage.Calculate();

                var machineResources = new MachineResources
                {
                    TotalMemory     = memInfo.TotalPhysicalMemory.GetValue(SizeUnit.Bytes),
                    AvailableMemory = memInfo.AvailableMemory.GetValue(SizeUnit.Bytes),
                    AvailableWithoutTotalCleanMemory = memInfo.AvailableWithoutTotalCleanMemory.GetValue(SizeUnit.Bytes),
                    SystemCommitLimit     = memInfo.TotalCommittableMemory.GetValue(SizeUnit.Bytes),
                    CommittedMemory       = memInfo.CurrentCommitCharge.GetValue(SizeUnit.Bytes),
                    ProcessMemoryUsage    = workingSet,
                    IsWindows             = PlatformDetails.RunningOnPosix == false,
                    IsLowMemory           = isLowMemory,
                    LowMemoryThreshold    = LowMemoryNotification.Instance.LowMemoryThreshold.GetValue(SizeUnit.Bytes),
                    CommitChargeThreshold = LowMemoryNotification.Instance.GetCommitChargeThreshold(memInfo).GetValue(SizeUnit.Bytes),
                    MachineCpuUsage       = cpuInfo.MachineCpuUsage,
                    ProcessCpuUsage       = Math.Min(cpuInfo.MachineCpuUsage, cpuInfo.ProcessCpuUsage) // min as sometimes +-1% due to time sampling
                };

                return(machineResources);
            }
        }
        public static MachineResources GetMachineResources()
        {
            var currentProcess = Process.GetCurrentProcess();
            var workingSet     =
                PlatformDetails.RunningOnPosix == false || PlatformDetails.RunningOnMacOsx
                    ? currentProcess.WorkingSet64
                    : MemoryInformation.GetRssMemoryUsage(currentProcess.Id);
            var memoryInfoResult = MemoryInformation.GetMemoryInfo();
            var installedMemory  = memoryInfoResult.InstalledMemory.GetValue(SizeUnit.Bytes);
            var availableMemory  = memoryInfoResult.AvailableMemory.GetValue(SizeUnit.Bytes);
            var mappedSharedMem  = LowMemoryNotification.GetCurrentProcessMemoryMappedShared();
            var shared           = mappedSharedMem.GetValue(SizeUnit.Bytes);

            var cpuInfo          = CpuUsage.Calculate();
            var machineResources = new MachineResources
            {
                TotalMemory        = installedMemory,
                MachineMemoryUsage = installedMemory - availableMemory,
                ProcessMemoryUsage = workingSet,
                ProcessMemoryExcludingSharedUsage = Math.Max(workingSet - shared, 0),
                MachineCpuUsage = cpuInfo.MachineCpuUsage,
                ProcessCpuUsage = cpuInfo.ProcessCpuUsage
            };

            return(machineResources);
        }
Exemplo n.º 4
0
        private static DynamicJsonValue MemoryStatsInternal()
        {
            using (var currentProcess = Process.GetCurrentProcess())
            {
                var workingSet =
                    PlatformDetails.RunningOnPosix == false || PlatformDetails.RunningOnMacOsx
                        ? currentProcess.WorkingSet64
                        : MemoryInformation.GetRssMemoryUsage(currentProcess.Id);
                var memInfo = MemoryInformation.GetMemoryInfo();

                long totalMapping          = 0;
                var  fileMappingByDir      = new Dictionary <string, Dictionary <string, ConcurrentDictionary <IntPtr, long> > >();
                var  fileMappingSizesByDir = new Dictionary <string, long>();
                foreach (var mapping in NativeMemory.FileMapping)
                {
                    var dir = Path.GetDirectoryName(mapping.Key);

                    if (fileMappingByDir.TryGetValue(dir, out Dictionary <string, ConcurrentDictionary <IntPtr, long> > value) == false)
                    {
                        value = new Dictionary <string, ConcurrentDictionary <IntPtr, long> >();
                        fileMappingByDir[dir] = value;
                    }
                    value[mapping.Key] = mapping.Value;
                    foreach (var singleMapping in mapping.Value)
                    {
                        fileMappingSizesByDir.TryGetValue(dir, out long prevSize);
                        fileMappingSizesByDir[dir] = prevSize + singleMapping.Value;
                        totalMapping += singleMapping.Value;
                    }
                }

                var prefixLength = LongestCommonPrefixLength(new List <string>(fileMappingSizesByDir.Keys));

                var fileMappings = new DynamicJsonArray();
                foreach (var sizes in fileMappingSizesByDir.OrderByDescending(x => x.Value))
                {
                    if (fileMappingByDir.TryGetValue(sizes.Key, out Dictionary <string, ConcurrentDictionary <IntPtr, long> > value))
                    {
                        var details = new DynamicJsonValue();

                        var dir = new DynamicJsonValue
                        {
                            [nameof(MemoryInfoMappingItem.Directory)]                = sizes.Key.Substring(prefixLength),
                            [nameof(MemoryInfoMappingItem.TotalDirectorySize)]       = sizes.Value,
                            [nameof(MemoryInfoMappingItem.HumaneTotalDirectorySize)] = Size.Humane(sizes.Value),
                            [nameof(MemoryInfoMappingItem.Details)] = details
                        };
                        foreach (var file in value.OrderBy(x => x.Key))
                        {
                            long totalMapped = 0;
                            var  dja         = new DynamicJsonArray();
                            var  dic         = new Dictionary <long, long>();
                            foreach (var mapping in file.Value)
                            {
                                totalMapped += mapping.Value;
                                dic.TryGetValue(mapping.Value, out long prev);
                                dic[mapping.Value] = prev + 1;
                            }
                            foreach (var maps in dic)
                            {
                                dja.Add(new DynamicJsonValue
                                {
                                    [nameof(MemoryInfoMappingDetails.Size)]  = maps.Key,
                                    [nameof(MemoryInfoMappingDetails.Count)] = maps.Value
                                });
                            }
                            var fileSize = GetFileSize(file.Key);
                            details[Path.GetFileName(file.Key)] = new DynamicJsonValue
                            {
                                [nameof(MemoryInfoMappingFileInfo.FileSize)]          = fileSize,
                                [nameof(MemoryInfoMappingFileInfo.HumaneFileSize)]    = Size.Humane(fileSize),
                                [nameof(MemoryInfoMappingFileInfo.TotalMapped)]       = totalMapped,
                                [nameof(MemoryInfoMappingFileInfo.HumaneTotalMapped)] = Size.Humane(totalMapped),
                                [nameof(MemoryInfoMappingFileInfo.Mappings)]          = dja
                            };
                        }
                        fileMappings.Add(dir);
                    }
                }

                long totalUnmanagedAllocations = 0;
                var  threads = new DynamicJsonArray();
                foreach (var stats in NativeMemory.ThreadAllocations.Values
                         .Where(x => x.IsThreadAlive())
                         .GroupBy(x => x.Name)
                         .OrderByDescending(x => x.Sum(y => y.TotalAllocated)))
                {
                    var unmanagedAllocations = stats.Sum(x => x.TotalAllocated);
                    totalUnmanagedAllocations += unmanagedAllocations;
                    var ids = new DynamicJsonArray(stats.OrderByDescending(x => x.TotalAllocated).Select(x => new DynamicJsonValue
                    {
                        ["Id"] = x.UnmanagedThreadId,
                        ["ManagedThreadId"]   = x.Id,
                        ["Allocations"]       = x.TotalAllocated,
                        ["HumaneAllocations"] = Size.Humane(x.TotalAllocated)
                    }));
                    var groupStats = new DynamicJsonValue
                    {
                        ["Name"]              = stats.Key,
                        ["Allocations"]       = unmanagedAllocations,
                        ["HumaneAllocations"] = Size.Humane(unmanagedAllocations)
                    };
                    if (ids.Count == 1)
                    {
                        var threadStats = stats.First();
                        groupStats["Id"] = threadStats.UnmanagedThreadId;
                        groupStats["ManagedThreadId"] = threadStats.Id;
                    }
                    else
                    {
                        groupStats["Ids"] = ids;
                    }
                    threads.Add(groupStats);
                }
                var managedMemory = GC.GetTotalMemory(false);
                var djv           = new DynamicJsonValue
                {
                    [nameof(MemoryInfo.WorkingSet)] = workingSet,
                    [nameof(MemoryInfo.TotalUnmanagedAllocations)] = totalUnmanagedAllocations,
                    [nameof(MemoryInfo.ManagedAllocations)]        = managedMemory,
                    [nameof(MemoryInfo.TotalMemoryMapped)]         = totalMapping,
                    [nameof(MemoryInfo.PhysicalMem)]           = Size.Humane(memInfo.TotalPhysicalMemory.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.FreeMem)]               = Size.Humane(memInfo.AvailableMemory.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.HighMemLastOneMinute)]  = Size.Humane(memInfo.MemoryUsageRecords.High.LastOneMinute.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.LowMemLastOneMinute)]   = Size.Humane(memInfo.MemoryUsageRecords.Low.LastOneMinute.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.HighMemLastFiveMinute)] = Size.Humane(memInfo.MemoryUsageRecords.High.LastFiveMinutes.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.LowMemLastFiveMinute)]  = Size.Humane(memInfo.MemoryUsageRecords.Low.LastFiveMinutes.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.HighMemSinceStartup)]   = Size.Humane(memInfo.MemoryUsageRecords.High.SinceStartup.GetValue(SizeUnit.Bytes)),
                    [nameof(MemoryInfo.LowMemSinceStartup)]    = Size.Humane(memInfo.MemoryUsageRecords.Low.SinceStartup.GetValue(SizeUnit.Bytes)),

                    [nameof(MemoryInfo.Humane)] = new DynamicJsonValue
                    {
                        [nameof(MemoryInfoHumane.WorkingSet)] = Size.Humane(workingSet),
                        [nameof(MemoryInfoHumane.TotalUnmanagedAllocations)] = Size.Humane(totalUnmanagedAllocations),
                        [nameof(MemoryInfoHumane.ManagedAllocations)]        = Size.Humane(managedMemory),
                        [nameof(MemoryInfoHumane.TotalMemoryMapped)]         = Size.Humane(totalMapping)
                    },

                    ["Threads"] = threads,

                    [nameof(MemoryInfo.Mappings)] = fileMappings
                };
                return(djv);
            }
        }