好的,我正在使用ThreadPool来启动线程。在threaad代码中,我试图弄清楚它实际使用的cpu时间。我读过有ProcessThread。 TotalProcessorTime属性(http://msdn.microsoft.com/en-us/library/system.diagnostics.processthread.totalprocessortime.aspx)但我无法阅读它。那么我如何获得当前线程?
答案 0 :(得分:3)
我一直在尝试同样的事情......了解特定线程消耗了多少cpu。在下面的代码中,我能够识别正在执行WorkHard的当前线程。 但是,变量intitialTicks和finalTicks在执行难以计算的函数之前和之后都有currentProcessThread.TotalProcessorTime.Ticks,但两者都保持相同的值,因此差值为零
public void WorkHard()
{
long initialTicks, finalTicks, deltaTicks;
byte f;
bool threadFound;
ProcessThreadCollection currentProcessThreads;
ProcessThread currentProcessThread = null;
int m_currentThreadId = kernel32.GetCurrentThreadId();
while (m_keepWorking)
{
f = (byte)rnd.Next(31);
System.Threading.Thread.Sleep(f*25);
threadFound = false;
currentProcessThreads = Process.GetCurrentProcess().Threads;
foreach (ProcessThread t in currentProcessThreads)
{
if (t.Id == m_currentThreadId)
{
currentProcessThread = t;
threadFound = true;
break;
}
}
initialTicks = threadFound ? currentProcessThread.TotalProcessorTime.Ticks : 0;
fibonacci(f);
finalTicks = threadFound ? currentProcessThread.TotalProcessorTime.Ticks : 0;
deltaTicks = finalTicks - initialTicks;
lock (workerLogFile.BaseStream)
{
workerLogFile.WriteLine(string.Concat(m_minionName, " finished calculating fib(", f.ToString(), ") at ", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.ffff"), " on threadId[", m_currentThreadId.ToString(), "]. Process required ", finalTicks.ToString()," - ", initialTicks.ToString()," = ", deltaTicks.ToString(), " ticks"));
}
OnMinionDoneEvent(new minionEventArgs(String.Concat(m_minionName, ", on thread ", m_currentThreadId.ToString("000000"), ", done working on Fibonacci(", f.ToString(), ")"), finalTicks - initialTicks));
}
lock (workerLogFile.BaseStream)
{
workerLogFile.WriteLine(string.Concat(m_minionName, " called to rest at ", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.ffff"), " on threadId[", m_currentThreadId.ToString(), "]."));
}
答案 1 :(得分:2)
一些小说:
1)通过ProcessThread获取正确的进程线程。 TotalProcessorTime您需要本机线程ID
2)听起来非常类似于您将托管线程ID(通过Thread.CurrentThread.Name)与本机线程ID进行比较,以通过System.Diagnostics命名空间获取当前线程。请记住托管线程ID!= ProcessThreadID。您需要使用GetCurrentThreadId函数http://msdn.microsoft.com/en-us/library/ms683183(VS.85).aspx
3)线程池线程可以被回收,因此线程池的TotalProcessorTime可能比你预期的要大
4)如果您分析线程使用情况,可能更容易在Visual Studio Ultimate中使用线程分析器,或者使用其他优秀的分析器(即ANTS,DotTrace,SciTech)