Stopwatch是一个计时器类,一种方便的方法来测量代码块的执行时间。它是System.Diagnostics命名空间中的 一个类。
当使用Stopwatch类时,可以用来测量代码块的执行时间:
- 创建Stopwatch对象:
Stopwatch stopwatch = new Stopwatch();
- 启动计时器:在要测量执行时间的代码块之前,调用Start()方法来启动计时器
stopwatch.Start();
-
执行代码块:在Start()方法之后,执行需要测量执行时间的代码块。
-
停止计时器:在代码块执行完毕后,调用Stop()方法来停止计时器
stopwatch.Stop();
- 获取经过的时间:使用Elapsed属性来获取经过的时间。可以使用ElapsedMilliseconds属性来获取经过的毫秒数。
long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
- 重置计时器:如果需要多次测量不同代码块的执行时间,可以使用Reset()方法来重置计时器。
stopwatch.Reset();
演示如何使用Stopwatch类来测量代码块的执行时间:
//创建Stopwatch对象
Stopwatch stopwatch = new Stopwatch();
// 启动计时器
stopwatch.Start();
// 执行代码块
Console.WriteLine("开始执行代码块...");
// 模拟一段耗时的代码
System.Threading.Thread.Sleep(2000);
// 停止计时器
stopwatch.Stop();
// 获取经过的时间(毫秒)
long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
Console.WriteLine("代码块执行时间:" + elapsedMilliseconds + "毫秒");
// 重置计时器
stopwatch.Reset();
// 再次启动计时器
stopwatch.Start();
// 执行另一个代码块
Console.WriteLine("开始执行另一个代码块...");
// 模拟另一个耗时的代码
System.Threading.Thread.Sleep(3000);
// 停止计时器
stopwatch.Stop();
// 获取经过的时间(毫秒)
elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
Console.WriteLine("另一个代码块执行时间:" + elapsedMilliseconds + "毫秒");