Using PerformanceCounter to track memory and CPU usage per process?

前端 未结 3 1215
耶瑟儿~
耶瑟儿~ 2020-12-01 02:51

How can I use System.Diagnostics.PerformanceCounter to track the memory and CPU usage for a process?

相关标签:
3条回答
  • 2020-12-01 03:34

    For per process data:

    Process p = /*get the desired process here*/;
    PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
    PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
    while (true)
    {
        Thread.Sleep(500);
        double ram = ramCounter.NextValue();
        double cpu = cpuCounter.NextValue();
        Console.WriteLine("RAM: "+(ram/1024/1024)+" MB; CPU: "+(cpu)+" %");
    }
    

    Performance counter also has other counters than Working set and Processor time.

    0 讨论(0)
  • 2020-12-01 03:34

    If you are using .NET Core, the System.Diagnostics.PerformanceCounter is not an option. Try this instead:

    System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
    long ram = p.WorkingSet64;
    Console.WriteLine($"RAM: {ram/1024/1024} MB");
    
    0 讨论(0)
  • 2020-12-01 03:39

    I think you want Windows Management Instrumentation.

    EDIT: See here:

    Measure a process CPU and RAM usage

    How to get the CPU Usage in C#?

    0 讨论(0)
提交回复
热议问题