Mearsuring time execution of a method or algorithm
In C#, I've used the below class to measure time execution of a algorithm. The class is taken from the book "CLR via c#" by jeffrey.
internal sealed class OperationTimer : IDisposable
{
private Stopwatch m_stopwatch;
private String m_text;
private Int32 m_collectionCount;
public OperationTimer(String text)
{
PrepareForOperation();
m_text = text;
m_collectionCount = GC.CollectionCount(0);
// This should be the last statement in this
// method to keep timing as accurate as possible
m_stopwatch = Stopwatch.StartNew();
}
public void Dispose()
{
Console.WriteLine("{0} (GCs={1,3}) {2}", (m_stopwatch.Elapsed), GC.CollectionCount(0) - m_collectionCount, m_text);
}
private static void PrepareForOperation()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
Usage:
using (new OperationTimer("name"))
{
ArrayList a = new ArrayList();
for (Int32 n = 0; n < count; n++)
{
Console.WriteLine(n);
a.Add(n); // Boxing
Int32 x = (Int32)a[n]; // Unboxing
}
a = null; // Make sure this gets garbage collected
}
0 comments:
Post a Comment