Here is a series of classes I use to test elapsed times within NUnit
test. While I use these functions very rarely, they come in handy
when necessary. This gives me the ability to directly monitor
performance changes caused by inefficient code in a bug fix or feature
addition. Please note I've trimmed out pieces in the
AppTimer that deal with runtime performance logging and I'm throwing an
exception rather than performing an 'Assert.IsTrue(...)' function
call. The runtime performance logging is dropped to shorten the
discussion and the Assert class is ignored for the sake of not wanting
to bind to the NUnit.Framework in some conditions.
The code below shows an 'AppTimer' class that grabs the tick count
upon instantiation. The client code can then call
'BoundedTimeTest()' to declare the maximum time allowed for the
test. If the elapsed time (measured in milliseconds) is greater
than the requested maximum, then an AppTimerException is raised. As
noted earlier, I am throwing an AppTimerException which is used so the
test can rely upon [ExpectedException] attribute on the test function.
public class AppTimerException : System.Exception
{
public AppTimerException()
{
}
public AppTimerException(string Message) : base(Message)
{
}
public AppTimerException(string Message, Exception innerException) : base(Message, innerException)
{
}
}
public class AppTimer
{
int _StartTick;
public AppTimer()
{
_StartTick = Environment.TickCount;
}
private int GetElapsedTime()
{
return Environment.TickCount - _StartTick;
}
public void BoundedTimeTest( int TimeLimit )
{
int ElapsedTime = GetElapsedTime();
if( TimeLimit
{
string Message = string.Format("Elapsed time of {0} ms exceeded limit of {1} ms", ElapsedTime, TimeLimit );
throw new AppTimerException(Message);
}
}
}
The last
bit of code involves the bounded time checking for the test in
question. Note that the initial Load functionality is not timed
because this test only concerns itself with structural feasability.
CoreTest ct = new CoreTest();
Engine ime = ct.LoadIME();
AppTimer appTimer = new AppTimer();
foreach( BomHeader bomHeader in ime.bomEngine.bomHeaders.Values )
Assert.IsTrue(bomHeader.IsFeasable);
appTimer.BoundedTimeTest(500); // exception thrown if code takes longer than 500 milliseconds to process
Keep
in mind that timespan testing is used very rarely in a test suite (at
least mine), but these classes make implementation very easy.