Timer for Performance Testing
Wednesday, May 13th, 2009呢排重溫緊 Pragmatic Unit Testing in C# with Nunit, 開始試緊寫有關 Performance 既 Test Case, 書中有一段有關 Performance 既 Code:
[Test]
public void FilterRanges()
{
Timer timer = new Timer();
String naughty_url = "http://www.xxxxxxxxxxx.com";
// First, check a bad URL against a small list
URLFilter filter = new URLFilter(small_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 1.0);
// Next, check a bad URL against a big list
filter = new URLFilter(big_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 2.0);
// Finally, check a bad URL against a huge list
filter = new URLFilter(huge_list);
timer.Start();
filter.Check(naughty_url);
timer.End();
Assert.IsTrue(timer.ElapsedTime < 3.0);
}
段 code 係一個幾好既 example 去講點 Test Performance, 但當真係要試果陣, 就發現左樣野, 就係我搵唔到 Code 中既 Timer Class, 係我在 System 入面既幾個 namespace 中, 都搵唔到啱用既 Timer, 因為 System namespace 入面既 Timer 大部份都係用黎 Trigger Timeout Event, 而當中既 Stop method 都只係用黎停止 Event Trigger, 而沒有任何計時結果做到出黎, 所以經過一輪網上既搜尋之後, 得出以下 Timer, 主要目的係用黎計時, 仔細度高, 最啱用黎作 Performance Testing 之用!!~
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace TestUtil
{
public class HighResolutionTimer
{
private long frequency;
private long start;
private long stop;
public HighResolutionTimer()
{
QueryPerformanceFrequency(ref frequency);
}
public float ElapsedTime
{
get
{
float elapsed = (((float)(stop - start)) / ((float)frequency));
return elapsed;
}
}
public void Start()
{
QueryPerformanceCounter(ref start);
}
public void Stop()
{
QueryPerformanceCounter(ref stop);
}
[System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool QueryPerformanceCounter([In, Out] ref long performanceCount);
[System.Runtime.InteropServices.DllImport("KERNEL32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool QueryPerformanceFrequency([In, Out] ref long frequency);
}
}
HighResolutionTimer 來源 : 在 C# 中實現高性能計時
