一、用C#自帶的StopWatch函數

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StopWatch
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? Stopwatch sw = new Stopwatch();
??????????? sw.Start();
??????????? //這里填寫要執行的代碼
??????????? sw.Stop();
??????????? Console.WriteLine("總運行時間:" + sw.Elapsed);
??????????? Console.WriteLine("測量實例得出的總運行時間(毫秒為單位):" + sw.ElapsedMilliseconds);
??????????? Console.WriteLine("總運行時間(計時器刻度標識):" + sw.ElapsedTicks);
??????????? Console.WriteLine("計時器是否運行:" + sw.IsRunning.ToString());
??????? }
??? }
}

運行結果如下:
總運行時間:00:00:00.0000013
測量實例得出的程序運行時間(毫秒為單位):0
總運行時間(計時器刻度標識):5
計時器是否運行:False

?


二、用API函數QueryPerformanceFrequency

using ?System; ??

using ?System.Threading; ??

class ?Class1 ??

{ ??

????[System.Runtime.InteropServices.DllImport( "Kernel32.dll" )] ??

???? static ? extern ? bool ?QueryPerformanceCounter( ref ? long ?count); ??

????[System.Runtime.InteropServices.DllImport( "Kernel32.dll" )] ??

???? static ? extern ? bool ?QueryPerformanceFrequency( ref ? long ?count); ??

????[STAThread] ??

???? static ? void ?Main( string []?args) ??

????{ ??

???????? long ?count?=?0; ??

???????? long ?count1?=?0; ??

???????? long ?freq?=?0; ??

???????? double ?result?=?0; ??

????????QueryPerformanceFrequency( ref ?freq); ??

????????QueryPerformanceCounter( ref ?count); ??

???????? //需要測試的模塊 ??

??

???????? int ?heisetoufa; ??

???????? for ?(heisetoufa?=?1;?heisetoufa?<?10000;?heisetoufa++) ??

????????{ ??

????????????Console.WriteLine( "第" ?+?heisetoufa?+? "行" ); ??

???????????? if ?(heisetoufa?==?5000) ??

????????????{ ??

????????????????Thread.Sleep(10000); ??

????????????} ??

????????} ??

??

???????? //需要測試的模塊 ??

??

????????QueryPerformanceCounter( ref ?count1); ??

????????count?=?count1?-?count; ??

????????result?=?( double )(count)?/?( double )freq; ??

????????Console.WriteLine( "耗時:?{0}?秒" ,?result); ??

????????Console.ReadLine(); ??

????} ??

}??