共计 1307 个字符,预计需要 4 分钟阅读。
介绍[code]Stopwatch[/code]
-
- 命名空间:
- System.
Diagnostics
- Assemblies:
- System.Runtime.Extensions.dll, System.dll, netstandard.dll
提供一组方法和属性,可用于准确地测量运行时间。public class Stopwatch- 继承
-
Stopwatch
更多内容请点击
[wailian]https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.stopwatch?redirectedfrom=MSDN&view=netframework-4.8[/wailian]
使用方法
开始计时
//初始化新实例
Stopwatch sw = new Stopwatch();
//开始计时
sw.Start();
停止计时
sw.Stop();
[v_error]多次测量时默认返回的是总时间,若要获得单次时间,必须先调用Reset()[/v_error]
获取时间
| 属性名称 | 返回值 | 含义 |
| [code]Elapsed[/code] | [code]TimeSpan[/code] | 表示当前实例测量得出的总运行时间。 |
| [code]ElapsedMilliseconds[/code] | [code]Int64[/code] | 表示当前实例测量得出的总毫秒数。 |
| [code]ElapsedMilliseconds[/code] | [code]Int64[/code] | 表示当前实例测量得出的计时器计时周期的总数。 |
实例
并行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();
}
}
}
正文完



