C#之系统内存CPU

2/2/2024 CSharp

# 效果演示

mixureSecure

# 代码

public class MySystemInfo
{
	private PerformanceCounter allCPUCounter;

	private PerformanceCounter curCPUCounter;

	private PerformanceCounter curMenoryCounter;

	public MySystemInfo()
    {
		Process process = Process.GetCurrentProcess();
		string pname = process.ProcessName;
		allCPUCounter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
		curCPUCounter = new PerformanceCounter("Process", "% Processor Time", pname, true);
		curMenoryCounter = new PerformanceCounter("Process", "Working Set - Private", pname);
	}

	public double GetAllCPU()
	{
		double allCpu = allCPUCounter.NextValue();
		allCpu = Math.Min(100, allCpu);
		double CpuValue = Math.Round(allCpu, 1);
		Console.WriteLine($"CUP总使用百分比:{CpuValue}%");
		return CpuValue;
	}

	//public double GetCurrentProcessCPU()
	//{
	//	double curCpuVale = curCPUCounter.NextValue();
	//	curCpuVale = curCpuVale / Environment.ProcessorCount;
	//	curCpuVale = Math.Round(curCpuVale, 1);
	//	string CurProccCpuValue = $"{curCpuVale} %";
	//	Console.WriteLine($"当前进程CPU占比:{CurProccCpuValue}");
	//	return curCpuVale;
	//}

	public void GetAllMemory()
	{
		MemoryValue memory = MemoryHelper.GetMemoryValue();
		double allMemory = memory.TotalPhysicalMemory / 1024d / 1024d / 1024d;
		allMemory = Math.Round(allMemory, 2);
		Console.WriteLine($"总内存大小:{allMemory}G");
	}

	public double GetUsedMemory()
	{
		MemoryValue memory = MemoryHelper.GetMemoryValue();
		double useMemory = memory.UsedPhysicalMemory / 1024d / 1024d / 1024d;
		useMemory = Math.Round(useMemory, 2);
		Console.WriteLine($"已使用内存大小:{useMemory}G");
		return useMemory;
	}

	//public string GetCurrentProcessMemory()
	//{
	//	return GetCurMemorySize();
	//}

	//private string GetCurMemorySize()
	//{
	//	double size = curMenoryCounter.NextValue();
	//	size = size / 1024d / 1024d;
	//	if (size < 1024d)
	//	{
	//		size = Math.Round(size, 2);
	//		Console.WriteLine($"当前进程占用内存大小:{size.ToString() + "M"}");
	//		return size.ToString() + "M";
	//	}
	//	size = size / 1024d;
	//	size = Math.Round(size, 2);
	//	Console.WriteLine($"当前进程占用内存大小:{size.ToString() + "G"}");
	//	return size.ToString() + "G";
	//}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using SystemInfoDemo;

MySystemInfo mySystemInfo = new MySystemInfo();

while (true)
{
	Console.WriteLine("=================");
	mySystemInfo.GetAllCPU();
	//mySystemInfo.GetCurrentProcessCPU();
	mySystemInfo.GetAllMemory();
	mySystemInfo.GetUsedMemory();
	//mySystemInfo.GetCurrentProcessMemory();
	Console.ReadKey();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14