internal class HiPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter( out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency( out long lpFrequency); private long startTime, stopTime; private long freq; // 构造函数 public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { // 不支持高性能计数器 throw new Win32Exception(); } } // 开始计时器 public void Start() { // 来让等待线程工作 Thread.Sleep(0); QueryPerformanceCounter(out startTime); } // 停止计时器 public void Stop() { QueryPerformanceCounter(out stopTime); } // 返回计时器经过时间(单位:秒) public double Duration { get { return (double)(stopTime - startTime) / (double)freq; } } } 使用示例: HiPerfTimer pt = new HiPerfTimer(); // 创建新的 HiPerfTimer 对象 pt.Start(); // 启动计时器 Console.WriteLine("Test\n"); // 需要计时的代码 pt.Stop(); // 停止计时器 Console.WriteLine("Duration: {0} sec\n", pt.Duration); // 打印需要计时部分代码的用时
文章转载自:http://topic.csdn.net/u/20120514/16/0235fd54-b240-4035-90a5-04960c52524a.html?4312