Using the Stopwatch to mesaure abstract method run time
I would like to create an abstract class with an abstract method which can measure how long it takes to run.
public abstract class Monitor
{
protected Stopwatch Timer = Stopwatch.StartNew();
public abstract void Run();
}
public class Concrete : Monitor
{
public override void Run()
{
base.Timer.Start();
//DoSomething
base.Timer.Stop();
}
}
However, implementers of the abstract class should not be calling the Start / Stop methods directly, so we can try to hide the implementation.
public abstract class Monitor
{
private Stopwatch Timer = Stopwatch.StartNew();
public virtual void Run()
{
Timer.Start();
Timer.Stop();
}
}
But as you can see this won't work very well.
How can i ensure that all implementations of the base class will call Start 开发者_JAVA技巧/Stop and yet allow implementation code to run in between? Could events help me here, if so how?
Use the template method pattern:
public abstract class Monitor
{
private readonly Stopwatch Timer = new Stopwatch();
public void Run()
{
Timer.Start();
DoRun();
Timer.Stop();
}
protected abstract void DoRun();
}
You could just do it like this:
public abstract class Monitor
{
protected Stopwatch Timer = Stopwatch.StartNew();
public abstract void Run();
public void Test()
{
Timer.Start();
Run();
Timer.End();
}
}
public class Concrete : Monitor
{
public override void Run()
{
//DoSomething
}
}
You have the overhead of the virtual call in there, but it should be small. To alleviate that cost, you can just do some warm up calls and then do the actual timing call. This also has the benefit of letting JIT run and do it's optimization. For example:
public abstract class Monitor
{
protected Stopwatch Timer = Stopwatch.StartNew();
public abstract void Run();
public void Test()
{
// Warm up to let JIT do it's magic.
for (int i = 0; i < 1000; i++)
Run();
Timer.Start();
Run();
Timer.End();
}
}
I remember reading in an answer a while back, you should aim to try to do at least 1 to 1.5 seconds worth of looping the function you want to benchmark.
精彩评论