測試程序運行時間 (轉)
原文: http://www.cnblogs.com/kavilee/archive/2010/12/13/1904274.html
一、用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(); ??
????} ??
}??
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
