【C#教程】停表-StopWatch

9,889次阅读
没有评论

共计 1307 个字符,预计需要花费 4 分钟才能阅读完成。

引子

看到标题,你可能会摸不清这篇文章的内容.你以为文章要讲这个吗?

【C#教程】停表-StopWatch

NO!是这个

【C#教程】停表-StopWatch

介绍[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();
        }
    }
}

【C#教程】停表-StopWatch

正文完
 
lvshujun
版权声明:本站原创文章,由 lvshujun 2019-09-13发表,共计1307字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请联系站长并注明出处。
评论(没有评论)