簡體   English   中英

如何在C#(托管代碼)中獲得* THREAD *的CPU使用率和/或RAM使用率?

[英]How can I get CPU usage and/or RAM usage of a *THREAD* in C# (managed code)?

我知道如何獲得進程的CPU使用率和內存使用率,但我想知道如何在每個線程級別上獲取它。 如果最好的解決方案是做一些P-Invoking,那也沒關系。

我需要的例子:

Thread myThread = Thread.CurrentThread;

// some time later in some other function...

Console.WriteLine(GetThreadSpecificCpuUsage(myThread));

如上所述,內存使用無法回答,因為這是整個過程的一個屬性,但CPU使用:

Process p = Process.GetCurrentProcess(); // getting current running process of the app
foreach (ProcessThread pt in p.Threads)
{
    // use pt.Id / pt.TotalProcessorTime / pt.UserProcessorTime / pt.PrivilegedProcessorTime
}

您無法獲得每個線程的內存使用量,因為內存在進程中的所有線程之間共享。 操作系統如何知道您是否在一個線程中分配了內存並在另一個線程中使用了它。 這意味着什么?

這是一個做你想做的事的例子http://www.codeproject.com/KB/system/processescpuusage.aspx

這是一個簡單的程序,它啟動5個消耗不同CPU數量的線程,然后匹配哪個托管線程消耗了多少CPU。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

class Program
{
[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();

static void Main(string[] args)
{
    Dictionary<int, Thread> threads = new Dictionary<int, Thread>();

    // Launch the threads
    for (int i = 0; i < 5; i++)
    {
        Thread cpuThread = new Thread((start) =>
        {
            lock (threads)
            {
                threads.Add(GetCurrentWin32ThreadId(), Thread.CurrentThread);
            }

            ConsumeCPU(20 * (int)start);
        });
        cpuThread.Name = "T" + i;
        cpuThread.Start(i);
    }

    // Every second wake up and see how much CPU each thread is using.
    Thread monitoringThread = new Thread(() =>
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            while (true)
            {
                Thread.Sleep(1000);
                Console.Write("\r");

                double totalTime = ((double)watch.ElapsedMilliseconds);
                if (totalTime > 0)
                {
                    Process p = Process.GetCurrentProcess();
                    foreach (ProcessThread pt in p.Threads)
                    {
                        Thread managedThread;
                        if (threads.TryGetValue(pt.Id, out managedThread))
                        {
                            double percent = (pt.TotalProcessorTime.TotalMilliseconds / totalTime);
                            Console.Write("{0}-{1:0.00} ", managedThread.Name, percent);
                        }
                    }
                }
            }
        });
    monitoringThread.Start();
}


// Helper function that generates a percentage of CPU usage
public static void ConsumeCPU(int percentage)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    while (true)
    {
        if (watch.ElapsedMilliseconds > percentage)
        {
            Thread.Sleep(100 - percentage);
            watch.Reset();
            watch.Start();
        }
    }
}
}

請注意,CLR可能會更改托管線程正在執行的本機線程。 但是,在實踐中,我不確定這種情況經常發生的頻率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM