C # gets CPU and memory usage

Original: C#Get CPU and memory usage rate

Get memory usage rate

Method 1:

share picture

using System;

using System.Runtime.InteropServices;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
Console.WriteLine(
"Total memory:" + FormatSize(GetTotalPhys()));
Console.WriteLine(
"Used:" + FormatSize(GetUsedPhys()));
Console.WriteLine(
"Available:" + FormatSize(GetAvailPhys()));
Console.ReadKey();
}

#region Get memory information API
[DllImport(
"kernel32.dll")]
[
return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);

//Define the information structure of the memory
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength; //Current structure size
public uint dwMemoryLoad; //Current memory usage
public ulong ullTotalPhys; //Total physical memory size
public ulong ullAvailPhys; //Available physical memory size
public ulong ullTotalPageFile; //Total swap file size
public ulong ullAvailPageFile; //Total swap file size
public ulong ullTotalVirtual; //Total virtual memory size
public ulong ullAvailVirtual; //Available virtual memory size
public ulong ullAvailExtendedVirtual; //Keep this value always at 0
}
#endregion

#region Format the size
///
/// Format the size
///

/// Capacity (B)
/// formatted capacity
private static string FormatSize(double size)
{
double d = (double)size;
int i = 0;
while ((d> 1024) && (i <5))
{
d
/= 1024;
i
++;
}
string[] unit = {"B", "< span style="color: #800000;">KB", "MB", "< /span>GB", "TB" };
return (string.Format("{0} {1}", Math.Round(d, 2), unit[i]));
}
#endregion

#region Get the current memory usage
///
/// Get the current memory usage
///

///
public static MEMORY_INFO GetMemoryStatus()
{
MEMORY_INFO mi
= new MEMORY_INFO();
mi.dwLength
= (uint)System.Runtime.InteropServices.Marshal .SizeOf(mi);
GlobalMemoryStatusEx(
ref mi);
return mi;
}
#endregion

#region Get the current available physical memory size
///
/// Get the current available physical memory size
///

/// Currently available physical memory (B)
public static ulong GetAvailPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullAvailPhys;
}
#endregion

#region Get the currently used memory size
///
/// Get the currently used memory size
///

/// Used memory size (B)
public static ulong GetUsedPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return (mi.ullTotalPhys - mi.ullAvailPhys);
}
#endregion

#region Get the current total physical memory size
///
/// Get the current total physical memory size
///

/// public static ulong GetTotalPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullTotalPhys;
}
#endregion
}
}

View Code

Method 2: p>

Note: Need to add a reference to System.Management

share Image

using System;

using System.Management;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
// Need to add a reference to System.Management


//Get the total physical memory size
ManagementClass cimobject1 = new ManagementClass("Win32_PhysicalMemory");
ManagementObjectCollection moc1
= cimobject1.GetInstances();
double available=0, capacity=0;
foreach (ManagementObject mo1 in moc1)
{
capacity
+= ((Math.Round(Int64.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));
}
moc1.Dispose();
cimobject1.Dispose();


//Get the available memory size
ManagementClass cimobject2 = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
ManagementObjectCollection moc2
= cimobject2.GetInstances();
foreach (ManagementObject mo2 in moc2)
{
available
+= ((Math.Round(Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString()) / 1024.0 span>, 1)));

}
moc2.Dispose();
cimobject2.Dispose();

Console.WriteLine(
"Total memory=" + capacity.ToString() + "G");
Console.WriteLine(
"Available=" + available.ToString() + "G");
Console.WriteLine(
"used=" + ((capacity-available)).ToString() + "G," + (Math.Round((capacity-available) / capacity * 100, 0)).ToString() + "< /span>%") ;
Console.ReadKey();
}
}
}

View Code

< h1>Get CPU usage rate

Share picture

using< span style="color: #000000;"> System;

using System.Diagnostics;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter
= new PerformanceCounter();
cpuCounter.CategoryName
= "Processor";
cpuCounter.CounterName
= "% Processor Time";
cpuCounter.InstanceName
= "_Total";
cpuCounter
= new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter
= new PerformanceCounter("Memory", "Available MBytes");



Console.WriteLine(
"Computer CPU usage: " + cpuCounter.NextValue() + "%");
Console.WriteLine(
"Computer available memory: " + ramCounter.NextValue() + "MB");
Console.WriteLine();



while (true)
{
System.Threading.Thread.Sleep(
1000);
Console.WriteLine(
"Computer CPU usage: " + cpuCounter.NextValue() + " %");
Console.WriteLine(
"Computer available memory: " + ramCounter.NextValue() + "MB");
Console.WriteLine();

if ((int)cpuCounter.NextValue() > 80)
{
System.Threading.Thread.Sleep(
1000 * 60);
}
}
}
}
}

View Code

< p>Related links:

  • C#Get computer model, system version, memory size, hard disk size, CPU information li>
  • About reading the system memory size in c#
  • C#Get CPU and memory usage of a specific process
  • C#Get CPU usage, memory usage, disk usage, process information< /span>
  • C# Obtain system CPU usage accurately
  • How to use C# to obtain CPU utilization in real time
  • C# uses WMI objects to obtain physical memory and available memory size information
  • C#Get system memory size

Share a picture

using System;

using System.Runtime.InteropServices;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
Console.WriteLine(
"Total memory:" + FormatSize(GetTotalPhys()));
Console.WriteLine(
"Used:" + FormatSize(GetUsedPhys()));
Console.WriteLine(
"Available:" + FormatSize(GetAvailPhys()));
Console.ReadKey();
}

#region Get memory information API
[DllImport(
"kernel32.dll")]
[
return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);

//Define the information structure of the memory
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength; //Current structure size
public uint dwMemoryLoad; //Current memory usage
public ulong ullTotalPhys; //Total physical memory size
public ulong ullAvailPhys; //Available physical memory size
public ulong ullTotalPageFile; //Total swap file size
public ulong ullAvailPageFile; //Total swap file size
public ulong ullTotalVirtual; //Total virtual memory size
public ulong ullAvailVirtual; //Available virtual memory size
public ulong ullAvailExtendedVirtual; //Keep this value always at 0
}
#endregion

#region Format the size
///
/// Format the size
///

/// Capacity (B)
/// formatted capacity
private static string FormatSize(double size)
{
double d = (double)size;
int i = 0;
while ((d> 1024) && (i <5))
{
d
/= 1024;
i
++;
}
string[] unit = {"B", "< span style="color: #800000;">KB", "MB", "< /span>GB", "TB" };
return (string.Format("{0} {1}", Math.Round(d, 2), unit[i]));
}
#endregion

#region Get the current memory usage
///
/// Get the current memory usage
///

///
public static MEMORY_INFO GetMemoryStatus()
{
MEMORY_INFO mi
= new MEMORY_INFO();
mi.dwLength
= (uint)System.Runtime.InteropServices.Marshal .SizeOf(mi);
GlobalMemoryStatusEx(
ref mi);
return mi;
}
#endregion

#region Get the current available physical memory size
///
/// 获得当前可用物理内存大小
///

/// 当前可用物理内存(B)
public static ulong GetAvailPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullAvailPhys;
}
#endregion

#region 获得当前已使用的内存大小
///
/// 获得当前已使用的内存大小
///

/// 已使用的内存大小(B)
public static ulong GetUsedPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return (mi.ullTotalPhys - mi.ullAvailPhys);
}
#endregion

#region 获得当前总计物理内存大小
///
/// 获得当前总计物理内存大小
///

/// public static ulong GetTotalPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullTotalPhys;
}
#endregion
}
}

View Code

using System;

using System.Runtime.InteropServices;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
Console.WriteLine(
"总内存:" + FormatSize(GetTotalPhys()));
Console.WriteLine(
"已使用:" + FormatSize(GetUsedPhys()));
Console.WriteLine(
"可使用:" + FormatSize(GetAvailPhys()));
Console.ReadKey();
}

#region 获得内存信息API
[DllImport(
"kernel32.dll")]
[
return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);

//定义内存的信息结构
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength; //当前结构体大小
public uint dwMemoryLoad; //当前内存使用率
public ulong ullTotalPhys; //总计物理内存大小
public ulong ullAvailPhys; //可用物理内存大小
public ulong ullTotalPageFile; //总计交换文件大小
public ulong ullAvailPageFile; //总计交换文件大小
public ulong ullTotalVirtual; //总计虚拟内存大小
public ulong ullAvailVirtual; //可用虚拟内存大小
public ulong ullAvailExtendedVirtual; //保留 这个值始终为0
}
#endregion

#region 格式化容量大小
///
/// 格式化容量大小
///

/// 容量(B)
/// 已格式化的容量
private static string FormatSize(double size)
{
double d = (double)size;
int i = 0;
while ((d > 1024) && (i < 5))
{
d
/= 1024;
i
++;
}
string[] unit = { "B", "KB", "MB", "GB", "TB" };
return (string.Format("{0} {1}", Math.Round(d, 2), unit[i]));
}
#endregion

#region 获得当前内存使用情况
///
/// 获得当前内存使用情况
///

///
public static MEMORY_INFO GetMemoryStatus()
{
MEMORY_INFO mi
= new MEMORY_INFO();
mi.dwLength
= (uint)System.Runtime.InteropServices.Marshal.SizeOf(mi);
GlobalMemoryStatusEx(
ref mi);
return mi;
}
#endregion

#region 获得当前可用物理内存大小
///
/// 获得当前可用物理内存大小
///

/// 当前可用物理内存(B)
public static ulong GetAvailPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullAvailPhys;
}
#endregion

#region 获得当前已使用的内存大小
///
/// 获得当前已使用的内存大小
///

/// 已使用的内存大小(B)
public static ulong GetUsedPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return (mi.ullTotalPhys - mi.ullAvailPhys);
}
#endregion

#region 获得当前总计物理内存大小
///
/// 获得当前总计物理内存大小
///

/// public static ulong GetTotalPhys()
{
MEMORY_INFO mi
= GetMemoryStatus();
return mi.ullTotalPhys;
}
#endregion
}
}

分享图片

using System;

using System.Management;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
//需要添加 System.Management 的引用


//获取总物理内存大小
ManagementClass cimobject1 = new ManagementClass("Win32_PhysicalMemory");
ManagementObjectCollection moc1
= cimobject1.GetInstances();
double available=0, capacity=0;
foreach (ManagementObject mo1 in moc1)
{
capacity
+= ((Math.Round(Int64.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));
}
moc1.Dispose();
cimobject1.Dispose();


//获取内存可用大小
ManagementClass cimobject2 = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
ManagementObjectCollection moc2
= cimobject2.GetInstances();
foreach (ManagementObject mo2 in moc2)
{
available
+= ((Math.Round(Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1)));

}
moc2.Dispose();
cimobject2.Dispose();

Console.WriteLine(
"总内存=" + capacity.ToString() + "G");
Console.WriteLine(
"可使用=" + available.ToString() + "G");
Console.WriteLine(
"已使用=" + ((capacity - available)).ToString() + "G," + (Math.Round((capacity - available) / capacity * 100, 0)).ToString() + "%");
Console.ReadKey();
}
}
}

View Code

using System;

using System.Management;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
//需要添加 System.Management 的引用


//获取总物理内存大小
ManagementClass cimobject1 = new ManagementClass("Win32_PhysicalMemory");
ManagementObjectCollection moc1
= cimobject1.GetInstances();
double available=0, capacity=0;
foreach (ManagementObject mo1 in moc1)
{
capacity
+= ((Math.Round(Int64.Parse(mo1.Properties["Capacity"].Value.ToString()) / 1024 / 1024 / 1024.0, 1)));
}
moc1.Dispose();
cimobject1.Dispose();


//获取内存可用大小
ManagementClass cimobject2 = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
ManagementObjectCollection moc2
= cimobject2.GetInstances();
foreach (ManagementObject mo2 in moc2)
{
available
+= ((Math.Round(Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString()) / 1024.0, 1)));

}
moc2.Dispose();
cimobject2.Dispose();

Console.WriteLine(
"总内存=" + capacity.ToString() + "G");
Console.WriteLine(
"可使用=" + available.ToString() + "G");
Console.WriteLine(
"已使用=" + ((capacity - available)).ToString() + "G," + (Math.Round((capacity - available) / capacity * 100, 0)).ToString() + "%");
Console.ReadKey();
}
}
}

分享图片

using System;

using System.Diagnostics;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter
= new PerformanceCounter();
cpuCounter.CategoryName
= "Processor";
cpuCounter.CounterName
= "% Processor Time";
cpuCounter.InstanceName
= "_Total";
cpuCounter
= new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter
= new PerformanceCounter("Memory", "Available MBytes");



Console.WriteLine(
"电脑CPU使用率:" + cpuCounter.NextValue() + "%");
Console.WriteLine(
"电脑可使用内存:" + ramCounter.NextValue() + "MB");
Console.WriteLine();



while (true)
{
System.Threading.Thread.Sleep(
1000);
Console.WriteLine(
"电脑CPU使用率:" + cpuCounter.NextValue() + " %");
Console.WriteLine(
"电脑可使用内存:" + ramCounter.NextValue() + "MB");
Console.WriteLine();

if ((int)cpuCounter.NextValue() > 80)
{
System.Threading.Thread.Sleep(
1000 * 60);
}
}
}
}
}

View Code

using System;

using System.Diagnostics;

namespace ConsoleApp1
{
public class Class1
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter
= new PerformanceCounter();
cpuCounter.CategoryName
= "Processor";
cpuCounter.CounterName
= "% Processor Time";
cpuCounter.InstanceName
= "_Total";
cpuCounter
= new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter
= new PerformanceCounter("Memory", "Available MBytes");



Console.WriteLine(
"电脑CPU使用率:" + cpuCounter.NextValue() + "%");
Console.WriteLine(
"电脑可使用内存:" + ramCounter.NextValue() + "MB");
Console.WriteLine();



while (true)
{
System.Threading.Thread.Sleep(
1000);
Console.WriteLine(
"电脑CPU使用率:" + cpuCounter.NextValue() + " %");
Console.WriteLine(
"电脑可使用内存:" + ramCounter.NextValue() + "MB");
Console.WriteLine();

if ((int)cpuCounter.NextValue() > 80)
{
System.Threading.Thread.Sleep(
1000 * 60);
}
}
}
}
}

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3081 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.