c# stopwatch的使用
时间: 2023-09-27 20:07:03 浏览: 213
C# 中的 Stopwatch 是一个计时器类,用于测量代码执行时间。它位于 System.Diagnostics 命名空间下。以下是 Stopwatch 的使用示例:
```csharp
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
// 启动计时器
stopwatch.Start();
// 执行需要计时的代码
YourMethodToMeasure();
// 停止计时器
stopwatch.Stop();
// 获取经过的时间
TimeSpan elapsedTime = stopwatch.Elapsed;
// 输出执行时间
Console.WriteLine("执行时间:{0}", elapsedTime);
// 重置计时器
stopwatch.Reset();
}
static void YourMethodToMeasure()
{
// 在此处编写需要计时的代码
}
}
```
在这个示例中,我们首先创建一个 Stopwatch 实例。然后,使用 Start() 方法启动计时器,并在 YourMethodToMeasure() 方法中编写需要计时的代码。之后,使用 Stop() 方法停止计时器,并使用 Elapsed 属性获取经过的时间。最后,我们可以将执行时间输出到控制台上。
希望以上信息对你有所帮助!如果你还有其他问题,请继续提问。
阅读全文
相关推荐
















