較準確的時間計算StopWatch及QueryPerformanceCounter
發表於 : 2009年 2月 18日, 16:34
在早期的 win32 程式上, 若要做較準確的時間計算, 可以使用 QueryPerformanceCounter 配合 QueryPerformanceFrequency 來達成, 不過在 .net 下, 可以使用較方便的 System.Diagnostics.StopWatch class 來進行.
他的方法很單純, 就是 new 出來後, 使用 Start(), Stop() 方法即可, 然後再取出時間屬性 ElapsedMilliseconds 就是較 DateTime 精確的 Milliseconds 了. 例如:
這樣就可以拿到了.
不過若是這樣還不夠, 可以使用原舊有的 Windows API 的 QueryPerformanceCounter 及 QueryPerformanceFrequency , 我們可以參考在 codeproject 網站上已經實作好的 HiPerfTimer class, http://www.codeproject.com/KB/cs/highpe ... cshar.aspx
利用這個 class 將可以取得更多位數的 Milliseconds 的精確時間.
使用方式:
他的方法很單純, 就是 new 出來後, 使用 Start(), Stop() 方法即可, 然後再取出時間屬性 ElapsedMilliseconds 就是較 DateTime 精確的 Milliseconds 了. 例如:
代碼: 選擇全部
using System.Diagnostics;
Stopwatch st = new Stopwatch();
st.Start();
//something want to check ....
st.Stop();
MessageBox.Show(st.ElapsedMilliseconds.ToString());
不過若是這樣還不夠, 可以使用原舊有的 Windows API 的 QueryPerformanceCounter 及 QueryPerformanceFrequency , 我們可以參考在 codeproject 網站上已經實作好的 HiPerfTimer class, http://www.codeproject.com/KB/cs/highpe ... cshar.aspx
利用這個 class 將可以取得更多位數的 Milliseconds 的精確時間.
代碼: 選擇全部
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
namespace Win32
{
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;
// Constructor
public HiPerfTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
// high-performance counter not supported
throw new Win32Exception();
}
}
// Start the timer
public void Start()
{
// lets do the waiting threads there work
Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
// Stop the timer
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
// Returns the duration of the timer (in seconds)
public double Duration
{
get
{
return (double)(stopTime - startTime) / (double) freq;
}
}
}
}
代碼: 選擇全部
HiPerfTimer pt = new HiPerfTimer(); // create a new PerfTimer object
pt.Start(); // start the timer
Console.WriteLine("Testn"); // the code to be timed
pt.Stop(); // stop the timer
Console.WriteLine("Duration: {0} secn",
pt.Duration); // print the duration of the timed code