代码之家  ›  专栏  ›  技术社区  ›  Timothy Khouri

如何获取C#(托管代码)中*THREAD*的CPU使用率和/或RAM使用率?

  •  13
  • Timothy Khouri  · 技术社区  · 17 年前

    我知道如何获取进程的CPU使用率和内存使用率,但我想知道如何在每个线程级别获取它。如果最好的解决方案是进行一些P-调用,那么这也很好。

    Thread myThread = Thread.CurrentThread;
    
    // some time later in some other function...
    
    Console.WriteLine(GetThreadSpecificCpuUsage(myThread));
    
    4 回复  |  直到 17 年前
        1
  •  3
  •   Tetraneutron    17 年前

    如上所述,内存使用无法回答,因为这是整个进程的一个属性,但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
    }
    
        2
  •  10
  •   developer82    11 年前

    您无法获取每个线程的内存使用情况,因为内存在进程中的所有线程之间共享。操作系统如何知道您是否在一个线程中分配了内存,并在另一个线程中将其使用。这意味着什么?

        3
  •  7
  •   erikkallen    17 年前

    这里有一个例子,可以做你想做的事 http://www.codeproject.com/KB/system/processescpuusage.aspx

        4
  •  2
  •   Lee Jensen    9 年前

    这是一个简单的程序,它启动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可能会更改托管线程正在执行的本机线程。然而,在实践中,我不确定这种情况实际发生的频率。