如何跟踪进程内存和CPU?

时间:2016-06-27 05:34:03

标签: c# asp.net-mvc performancecounter

获取进程的CPU和内存使用量的过程是什么?我必须通过什么价值观?

Process p = new Process();
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) + " %");
    Console.ReadLine();
}

1 个答案:

答案 0 :(得分:2)

对于Process,您可以使用静态方法GetCurrentProcess。结果进入了性能计数器。

在以下控制器中,PerformanceCounters创建一次然后重新使用。定时器保证在第一次调用之前已经过了500毫秒。

public class PerformanceController : Controller
{
    static PerformanceCounter ramCounter;
    static PerformanceCounter cpuCounter;

    static Timer timer;
    static ManualResetEvent waiter = new ManualResetEvent(false);

    static Performance lastMeasure = new Performance(); // the Model (in Mvc)

    static PerformanceController()
    {
        // Get the current process
        using (var p = Process.GetCurrentProcess())
        {
            ramCounter = new PerformanceCounter("Process", "Working Set", p.ProcessName);
            cpuCounter = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
        }
        // make sure some time has passed before first NextValue call
        timer = new Timer(s =>
        {
            waiter.Set();
        }, null, 500, Timeout.Infinite);

        // clean-up
        AppDomain.CurrentDomain.DomainUnload += (s, e) => {
            var time = (IDisposable)timer;
            if (time != null) time.Dispose();
            var wait = (IDisposable)waiter;
            if (wait != null) wait.Dispose();
            var rc = (IDisposable)ramCounter;
            if (rc != null) rc.Dispose();
            var cc = (IDisposable)cpuCounter;
            if (cc != null) cc.Dispose();
        };
    }

    private static  Performance GetReading()
    {
        // wait for the first reading 
        waiter.WaitOne();
        // maybe cache its values for a few seconds
        lastMeasure.Cpu = cpuCounter.NextValue();
        lastMeasure.Ram = ramCounter.NextValue();
        return lastMeasure;
    }

    //
    // GET: /Performance/
    public ActionResult Index()
    {
        return View(GetReading());
    }
}

性能模型非常简单:

public class Performance
{
    public double Ram { get; set; }
    public double Cpu { get; set; }
}

以下视图完成了实现

@model MvcApplication1.Models.Performance
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div><span>Ram</span><span>@Model.Ram</span> </div>
<div><span>Cpu</span><span>@Model.Cpu</span> </div>