2011-01-24 83 views
0

好吧,我正在使用ThreadPool启动线程。内部threaad代码我试图找出它实际使用的cpu时间。我读过了ProcessThread。这个TotalProcessorTime属性(http://msdn.microsoft.com/en-us/library/system.diagnostics.processthread.totalprocessortime.aspx)但我只是无法阅读它。那么如何获得当前线程呢?如何获取当前线程的ProcessThread.TotalProcessorTime

+0

你是什么意思“的意思是我刚无法读取它“? – 2011-01-24 17:57:18

回答

2

几点:

1)通过ProcessThread获取正确的进程线程。 TotalProcessorTime你需要本地线程ID

2)这听起来非常像你正在比较托管的线程ID(通过Thread.CurrentThread.Name)与本机线程ID以获取通过系统中的当前线程。诊断命名空间。请记住托管的线程ID!= ProcessThreadID。你需要使用GetCurrentThreadId功能http://msdn.microsoft.com/en-us/library/ms683183(VS.85).aspx

3)线程池中的线程可循环使用,所以你期待

4 TotalProcessorTime一个线程池可能大于)如果您剖析线程使用它可能更容易使用Visual Studio Ultimate中的线程分析器或另一个好的分析器(即蚂蚁,DotTrace,SciTech)

+0

是的,看来我一直在比较错误的东西。 – ren 2011-01-24 18:34:21

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(), "].")); 
     }