2009-06-01 56 views

回答

7

因爲內存進程中的所有線程之間共享你不能讓每個線程的內存使用情況是什麼。操作系統如何知道你是否在一個線程中分配內存並在另一個線程中使用它。這意味着什麼?

10

至於說,存儲器的使用不能被應答,因爲這是該過程作爲一個整體的屬性,但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 
} 
1

下面是一個簡單的程序,啓動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可能會更改託管線程正在執行的本地線程。但是,實際上我不確定這實際發生的頻率。

相關問題