gpt4 book ai didi

c# - 使用 StopWatch 类进行性能测试的辅助类

转载 作者:太空狗 更新时间:2023-10-29 19:51:59 26 4
gpt4 key购买 nike

在此示例代码中,我使用一个简单的秒表来测试完成给定任务/操作所需的时间

StopWatch SW1 = new StopWatch();
SW1.Start();
SomeAction();
SW1.Stop();
sting results = SW1.Elapsed.ToString();
MessageBox.Show(resutls);

我想要一个类,我将实例化以用于测试

public Class PerformanceTests
{
public StopWatch SW1 = new StopWatch();
public StopWatch SW2 = new StopWatch();
public string results1 = "", results2 = "";
....
....
//some other variables to use
}

尽管在实例化类并尝试使用 SW1 时不允许我使用它的方法。我做错了什么?

PerformanceTests Ptst = new PerformanceTests();
Ptst.SW1. ... Start() is not accessible

更新

对于其余的答案,不要复制我的代码,因为我错过了大写的 stopwatch。我没有实例化 Stopwatch 类,而是不小心没有注意到 Visual Studio 询问我是否要为我所谓的秒表而不是 .NET 的真正 Stopwatch 创建一个类。

所以我的建议,注意Visual Studio intellisense的建议操作即使它应该一直都是一样的。只要确保您真正有经验并牢记所有类(class)即可。

最佳答案

这是一个简单的类,可以帮助您测量代码块执行的时间:

public class PerformanceTester : IDisposable
{
private Stopwatch _stopwatch = new Stopwatch();
private Action<TimeSpan> _callback;

public PerformanceTester()
{
_stopwatch.Start();
}

public PerformanceTester(Action<TimeSpan> callback) : this()
{
_callback = callback;
}

public static PerformanceTester Start(Action<TimeSpan> callback)
{
return new PerformanceTester(callback);
}

public void Dispose()
{
_stopwatch.Stop();
if (_callback != null)
_callback(Result);
}

public TimeSpan Result
{
get { return _stopwatch.Elapsed; }
}
}

用法(使用 PerformanceTester 包装代码块):

using (var tester = new PerformanceTester())
{
// code to test
MessageBox.Show(tester.Results.ToString());
}

如果您在 using block 之前声明 tester 变量,那么秒表将在您退出 using block 时自动停止,并且您可以得到结果:

PerformanceTester tester;

using (tester = new PerformanceTester())
SomeAction();

MessageBox.Show(tester.Results.ToString());

如果您将回调操作传递给 PerformanceTester,则此操作将在 using 语句结束时调用,并将耗时传递给回调:

using (PerformanceTester.Start(ts => MessageBox.Show(ts.ToString())))
SomeAction();

您可以声明方法,它将接受TimeSpan 并处理结果:

private void ProcessResult(TimeSpan span)
{
// log, show, etc
MessageBox.Show(span.ToString());
}

用法变得非常干净:

using (PerformanceTester.Start(ProcessResult))
SomeAction();

关于c# - 使用 StopWatch 类进行性能测试的辅助类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13681664/

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