介绍Stopwatch
-
- 命名空间:
- System.
Diagnostics
- Assemblies:
- System.Runtime.Extensions.dll, System.dll, netstandard.dll
提供一组方法和属性,可用于准确地测量运行时间。
public class Stopwatch
- 继承
-
Stopwatch
更多内容请点击
Stopwatch 类 (System.Diagnostics) | Microsoft Docs
Stopwatch 类 (System.Diagnostics) | Microsoft Docs 跳转至主内容 此浏览器不再受支持。 请升级到 Microsoft Edge 以使用最新的功能、安全更新和技术支持。 下载 Microsoft Edge 更多信息 目录 退出焦点模式 语言 使用英语阅读
使用方法
开始计时
//初始化新实例
Stopwatch sw = new Stopwatch();
//开始计时
sw.Start();
停止计时
sw.Stop();
多次测量时默认返回的是总时间,若要获得单次时间,必须先调用Reset()
获取时间
sw.Stop();
多次测量时默认返回的是总时间,若要获得单次时间,必须先调用Reset()
获取时间
属性名称 | 返回值 | 含义 |
Elapsed |
TimeSpan |
表示当前实例测量得出的总运行时间。 |
ElapsedMilliseconds |
Int64 |
表示当前实例测量得出的总毫秒数。 |
ElapsedMilliseconds |
Int64 |
表示当前实例测量得出的计时器计时周期的总数。 |
实例
并行for循环与普通for循环效率比较
展开源代码
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace StopWatchPro { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); //多线程 ParallelLoopResult result = Parallel.For(0, 10000, i => { Console.Write(i); Thread.Sleep(1); }); sw.Stop(); Console.WriteLine("Parallel.For总共花费{0}ms.", sw.ElapsedMilliseconds); //单线程 sw.Reset(); sw.Start(); for (int i = 0; i < 10000; i++) { Console.Write(i); Thread.Sleep(1); } sw.Stop(); Console.WriteLine("for总共花费{0}ms.", sw.ElapsedMilliseconds); Console.ReadKey(); } } }
提示
你已经点赞过了