我想获得C#中应用程序的总CPU使用率.我已经找到了许多方法来深入研究进程的属性,但我只想要进程的CPU使用率,以及你在TaskManager中获得的总CPU.
我怎么做?
根据如何使用.NET PerformanceCounter来跟踪每个进程的内存和CPU使用情况? PerformanceCounter应该给我一个给定进程的内存使用次数.
根据MSDN,Process实例也可能给我或多或少相同的数字.
为了验证我的假设,我写了以下代码:
class Program
{
static Process process = Process.GetCurrentProcess();
static PerformanceCounter privateBytesCounter = new PerformanceCounter("Process", "Private Bytes", process.ProcessName);
static PerformanceCounter workingSetCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);
static void Main(string[] args)
{
GetMeasure();
Console.WriteLine("\nPress enter to allocate great amount of memory");
Console.ReadLine();
int[] arr = new int[10000000];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = i;
}
GetMeasure();
privateBytesCounter.Dispose();
workingSetCounter.Dispose();
Console.ReadKey();
}
private static void GetMeasure() …Run Code Online (Sandbox Code Playgroud)