使用秒表测量抽象方法的运行时间
我想创建一个带有抽象方法的抽象类,它可以测量运行时间。
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();
}
}
但是,抽象类的实现者不应该直接调用 Start / Stop 方法,因此我们可以尝试隐藏实现。
public abstract class Monitor
{
private Stopwatch Timer = Stopwatch.StartNew();
public virtual void Run()
{
Timer.Start();
Timer.Stop();
}
}
但正如你所看到的,这不会很好地工作。
我如何确保基类的所有实现都将调用 Start /Stop,但允许实现代码在其间运行?事件可以帮助我吗?如果可以的话,如何?
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 /Stop and yet allow implementation code to run in between? Could events help me here, if so how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用模板方法模式:
Use the template method pattern:
你可以这样做:
你有虚拟调用的开销,但它应该很小。
为了降低成本,您可以只进行一些热身调用,然后进行实际的计时调用。这还有一个好处是让 JIT 运行并进行优化。例如:
我记得不久前读过一个答案,您应该尝试至少花 1 到 1.5 秒的时间来循环您想要进行基准测试的函数。
You could just do it like this:
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:
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.