我想为我的单元测试做一个自定义断言,它将测量两个c#函数的执行时间并进行比较。 我已经编写了下面的代码,但还有更好的方法吗?
public static class AssertExtensions
{
public static void MoreSlowThan(Action slowFunction, Action fastFunction)
{
var watch = Stopwatch.StartNew();
slowFunction();
watch.Stop();
var watchBis = Stopwatch.StartNew();
fastFunction();
watchBis.Stop();
Assert.IsTrue(watch.ElapsedMilliseconds >= watchBis.ElapsedMilliseconds);
}
}
呼叫:
AssertExtensions.MoreSlowThan(() => MyFunction(), () => MyCachedFunction());
(目标是将函数的执行时间与缓存中相同函数的执行时间进行比较)
答案 0 :(得分:0)
我发现它的最佳方式是使用MSTest-2重构它,如:
public static void IsFaster(this Assert assert, Action expectedFastAction, Action actualSlowAction)
{
var slowStopwatch = Stopwatch.StartNew();
actualSlowAction();
slowStopwatch.Stop();
var fastStopwatch = Stopwatch.StartNew();
expectedFastAction();
fastStopwatch.Stop();
Assert.IsTrue(slowStopwatch.Elapsed >= fastStopwatch.Elapsed, string.Format("First function would be faster than the second. Fast function elapsed time : {0}. Slow function elapsed time : {1}", fastStopwatch.Elapsed, slowStopwatch.Elapsed));
}
并将其命名为:
Assert.That.IsSlower(() => MyCachedFunction(), () => MyFunction());
如果有人有更好的方式