如何获取C#(托管代码)中的* THREAD *的CPU使用率和/或RAM使用情况?
问题描述:
我知道如何获得一个进程的CPU使用率和内存使用量,但我想知道如何在每个线程级别获取它。如果最好的解决方案是做一些P-调用,那也没关系。什么,我需要如何获取C#(托管代码)中的* THREAD *的CPU使用率和/或RAM使用情况?
例子:
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
}
答
下面是一个简单的程序,启动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可能会更改托管线程正在执行的本地线程。但是,实际上我不确定这实际发生的频率。
这和我想我们要得到的一样接近......谢谢! – 2009-06-01 12:51:27
该链接不再有效 – 2016-07-18 05:03:33