2013年8月27日 星期二

【C#】計算CPU和記憶體使用情形 Calculate CPU and memory usage of process

如何讓程式邊執行邊計算CPU和記憶體使用率?

為了不讓程式可以更順暢的執行,

以下程式會開一個執行緒執行獨自計算。

如果要計算特定程式,只要將InstanceName改成程式名稱便可。

private Thread CpuAndMemoryThreadHandle;
private float cpuLoading = 0;
private float memoryLoading = 0;

private void Module_Load(object sender, EventArgs e)
{
    CpuAndMemoryThreadHandle = new Thread(CpuAndMemoryThread);
    CpuAndMemoryThreadHandle.Start();
}
private void timer_Tick(object sender, EventArgs e)
{    
    int cpuPercent = (int)cpuLoading;
    int memPercent = (int)memoryLoading;            
    Loading.Text = "CPU :" + cpuPercent + " % " + " " + " Memory :" + memPercent + " MB";       
}

private void CpuAndMemoryThread()
{

    PerformanceCounter cpuCounter = new PerformanceCounter();
    PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    cpuCounter.CategoryName = "Processor";//CPU
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";//All processors
    while(true)
    {                            
        System.Threading.Thread.Sleep(1000);               
        cpuLoading = cpuCounter.NextValue();
        memoryLoading = ramCounter.NextValue();
    }
  
}

0 意見:

張貼留言