C#获取某段代码的执行所消耗的时间

将需要统计时间的代码写道注释的位置,即可计算这段代码执行所消耗的时间

using System;


        static void Main(string[] args)
        {
            DateTime beforDT = System.DateTime.Now;
 
            //todo something
             //将需要计算的时间的代码写到这里即可

            DateTime afterDT = System.DateTime.Now;
            TimeSpan ts = afterDT.Subtract(beforDT);
            Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds);
            Console.WriteLine("DateTime总共花费{0}s.", ts.TotalSeconds);
            Console.ReadLine();
        }

posted @ 2023-11-02 23:19  先生沉默先  阅读(80)  评论(0)    收藏  举报