C# 精准获取代码运行时间

  纯粹转载,转载请注明参考链接及作者!

  参考链接:http://www.cnblogs.com/ret00100/archive/2010/08/06/1793680.html,作者:博客园 大佬辉

        http://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch_members(v=vs.80).aspx,MSDN

  可以使用.Net提供的Stopwatch类,它的命名空间是:System.Diagnostics

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication9
{
    class Program
    {

        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            // 开始测量代码运行时间
            sw.Start();
            
            // 要执行的代码
            int x = 5;
            for (int i = 0; i < 5;i++ )
                Console.Write(x);
            Console.WriteLine();

            // 结束测量
            sw.Stop();
            Console.WriteLine("总运行时间:" + sw.Elapsed);
            Console.WriteLine("测量实例得出的总运行时间(毫秒为单位):" + sw.ElapsedMilliseconds);
            Console.WriteLine("总运行时间(计时器刻度标识):" + sw.ElapsedTicks);
            Console.WriteLine("计时器是否运行:" + sw.IsRunning.ToString());
        }
    }
}

运行结果:

55555
总运行时间:00:00:00.0012360
测量实例得出的总运行时间(毫秒为单位):1
总运行时间(计时器刻度标识):3395
计时器是否运行:False
请按任意键继续. . .

  

原文地址:https://www.cnblogs.com/vitah/p/3977982.html