System.Diagnostics.Stopwatch
提供一组方法和属性,可用于准确地测量运行时间。
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
ProcessThread.ProcessorAffinity
设置关联线程可以在其上运行的处理器。
线程的处理器关联是线程与其有关系的一组处理器。 也就是可安排该线程在其上运行的那些处理器。
ProcessorAffinity将每个处理器表示为一位。位 0 表示处理器一,位 1 表示处理器二,以此类推。下表显示四处理器系统可能的ProcessorAffinity 的子集。
属性值(十六进制) | 有效的处理器 |
---|---|
0x0001 | 1 |
0x0002 | 2 |
0x0003 | 1 或 2 |
0x0004 | 3 |
0x0005 | 1 或 3 |
0x0007 | 1、2 或 3 |
0x000F | 1、2、3 或 4 |
ProcessThread.IdealProcessor
设置让此线程在其上运行的首选处理器。
using System;
using System.Diagnostics;
namespace ProcessThreadIdealProcessor
{
class Program
{
static void Main(string[] args)
{
// Make sure there is an instance of notepad running.
Process[] notepads = Process.GetProcessesByName("notepad");
if (notepads.Length == 0)
Process.Start("notepad");
ProcessThreadCollection threads;
//Process[] notepads;
// Retrieve the Notepad processes.
notepads = Process.GetProcessesByName("Notepad");
// Get the ProcessThread collection for the first instance
threads = notepads[0].Threads;
// Set the properties on the first ProcessThread in the collection
threads[0].IdealProcessor = 0;
threads[0].ProcessorAffinity = (IntPtr)1;
}
}
}