gpt4 book ai didi

c# - 单元测试 : Custom Timer Assert

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:12 25 4
gpt4 key购买 nike

我想为我的单元测试做一个自定义断言,它将测量两个 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());

(目标是比较一个函数的执行时间和缓存中同一个函数的执行时间)

最佳答案

我发现最好的方法是用 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());

谁有更好的办法

关于c# - 单元测试 : Custom Timer Assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com