关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

stopwatch对程序运行时间的准确测量

发布时间:2020-03-31 00:00:00

本文主要是讲解stopwatch对程序运行时间的准确测量

仅仅介绍里面的StartNew()方法,Restart()方法和ElapsedMilliseconds { get;}属性

public void对新的 System.Diagnostics.Stopwatch 实例进行初始化,将运行时间属性设置为零,然后开始测量运行时间。 
                            它的返回结果是刚刚开始测量运行时间的System.Diagnostics.Stopwatch。 停止时间间隔测量,将运行时间重置为零,然后开始测量运行时间。
public long ElapsedMilliseconds { get;}:作用是获取当前实例测量得出的总运行时间(以毫秒为单位)。 
                                        返回结果:一个只读长整型,表示当前实例测量得出的总毫秒数

 注意:在使用stopwatch时,命名空间需要引用using System.Diagnostics

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Diagnostics;using System.Threading;namespace SynchronizationProblems
{class Program
    {static void Main(string[] args)
        {int x = 0;const int iterationNumber = 5000000;
            Stopwatch sw = Stopwatch.StartNew();for(int i=0;i<iterationNumber;i++)
            {
                x++;
            }
            Console.WriteLine("不使用锁的情况下花费的时间:{0}ms",sw.ElapsedMilliseconds);
            sw.Restart();for (int i = 0; i < iterationNumber; i++)
            {
                Interlocked.Increment(ref x);
            }

            Console.WriteLine("使用锁的情况下花费的时间:{0}ms", sw.ElapsedMilliseconds);
            Console.Read();

        }
    }
}

运行环境是VS2017,运行结果为:

参考内容:
博客:https://www.cnblogs.com/vaevvaev/p/6929967.html
书籍:Learning hard C#学习笔记 (李志著)

/template/Home/Zkeys/PC/Static