假設CPU使用率和內存(進程工作集)的單個實例應用程序,你可以這樣做以下:
public static void Main(string[] args)
{
string processName = Process.GetCurrentProcess().ProcessName;
int processorCount = Environment.ProcessorCount;
// Simulate process usage
for (int i = 0; i < processorCount * 2; i++)
{
var t = new Thread(() =>
{
while (true) { Console.WriteLine("Busy..."); }
});
t.IsBackground = true;
t.Start();
}
var cpu = new PerformanceCounter("Process", "% Processor Time");
cpu.InstanceName = processName;
cpu.NextValue();
var ram = new PerformanceCounter("Process", "Working Set");
ram.InstanceName = processName;
float memUsage = (ram.NextValue()/1024)/1024;
Console.WriteLine("Memory Usage: {0}MB", memUsage);
float cpuUsage = cpu.NextValue()/(float)processorCount;
Console.WriteLine("CPU Usage: {0}%", cpuUsage);
}
對於CPU使用率性能計數器第一次調用NextValue
返回0,所以只有第二次調用用於顯示值。報告的使用量是所有機器處理器的總和,因此在顯示之前計算平均值。
「我不是在尋找第三方分析應用程序,我需要在我的應用程序中有數據」 - 這對我沒有意義嗎? – 2010-03-09 14:48:58
您正在討論一個分析器。要麼使用Visual Studio中內置的那個(如果你有這個版本),要麼使用像memprofiler這樣的東西。 – 2010-03-09 14:50:30
@Mitch:現在問題更清楚了嗎? – Simon 2010-03-09 14:59:06