一、用C#自帶的StopWatch函數(shù)

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();
??????????? //這里填寫要執(zhí)行的代碼
??????????? sw.Stop();
??????????? Console.WriteLine("總運(yùn)行時(shí)間:" + sw.Elapsed);
??????????? Console.WriteLine("測量實(shí)例得出的總運(yùn)行時(shí)間(毫秒為單位):" + sw.ElapsedMilliseconds);
??????????? Console.WriteLine("總運(yùn)行時(shí)間(計(jì)時(shí)器刻度標(biāo)識(shí)):" + sw.ElapsedTicks);
??????????? Console.WriteLine("計(jì)時(shí)器是否運(yùn)行:" + sw.IsRunning.ToString());
??????? }
??? }
}

運(yùn)行結(jié)果如下:
總運(yùn)行時(shí)間:00:00:00.0000013
測量實(shí)例得出的程序運(yùn)行時(shí)間(毫秒為單位):0
總運(yùn)行時(shí)間(計(jì)時(shí)器刻度標(biāo)識(shí)):5
計(jì)時(shí)器是否運(yùn)行:False

?


二、用API函數(shù)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( "耗時(shí):?{0}?秒" ,?result); ??

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

????} ??

}??