![](/img/trans.png)
[英]How to get % Memory usage of a process using Performnace Counter in C#
[英]How to use Performance Counter or Process class correctly in C# to get memory usage of current process?
根據如何使用.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()
{
Console.WriteLine("{0,38} {1,20}", "Private bytes", "working set");
Console.WriteLine("process data{0,23} {1,20}", process.PrivateMemorySize64 / 1024, process.WorkingSet64 / 1024);
Console.WriteLine("PerformanceCounter data{0,12} {1,20}", privateBytesCounter.NextValue() / 1024, workingSetCounter.NextValue() / 1024);
}
}
輸出看起來像
Private bytes working set
process data 22880 17516
PerformanceCounter data 21608 15608
Press enter to allocate great amount of memory
Private bytes working set
process data 22880 17516
PerformanceCounter data 21608 15608
一模一樣! 相比之下,Process Explorer中顯示的專用字節從32732增加到63620。
我做錯了什么?
您必須告訴您的process
實例它應刷新其緩存數據。 每次出於性能目的訪問屬性時,都不會收集數據。 您必須手動請求數據更新。
private static void GetMeasure()
{
process.Refresh(); // Updates process information
Console.WriteLine("{0,38} {1,20}", "Private bytes", "working set");
Console.WriteLine("process data{0,23} {1,20}", process.PrivateMemorySize64 / 1024, process.WorkingSet64 / 1024);
Console.WriteLine("PerformanceCounter data{0,12} {1,20}", privateBytesCounter.NextValue() / 1024, workingSetCounter.NextValue() / 1024);
}
那是你的process
。 對於性能計數器, NextValue()
應該每次都檢索一個新的新數據,所以我無法解釋為什么它不在你的機器上。 我的工作正常。
編輯 :
隨着process.Refresh()
添加,這是我得到的:
Private bytes working set
process data 25596 22932
PerformanceCounter data 26172 23600
Press enter to allocate great amount of memory
Private bytes working set
process data 65704 61848
PerformanceCounter data 65828 61880
警告:我的內存分析器(.NET Memory Profiler)顯示Process.Refresh()臨時分配了大量內存,因此如果您使用定時器定期讀取性能計數器,請記住這一點。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.