C#之计算程序运行耗时的方法

C#之计算程序运行耗时的方法

方式1 利用System.DateTime.Now

示例代码:

        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Now;
            int sum = 0;
            for (int i = 0; i < 1000; i++)
            {
                sum += 1;
            }
            DateTime dt2 = DateTime.Now;
            TimeSpan ts = dt2.Subtract(dt1);
            Console.WriteLine("程序耗时:{0}ms.", ts.TotalMilliseconds);
            Console.ReadLine();
        }

运行结果:

方式2 利用Stopwatch

示例代码:

        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int sum = 0;
            for (int i = 0; i < 1000; i++)
            {
                sum += 1;
            }
            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            Console.WriteLine("程序耗时:{0}ms.", ts.TotalMilliseconds);
            Console.ReadLine();
        }

运行结果:

方式3 利用API函数

示例代码:

        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        static extern bool QueryPerformanceCounter(ref long count);
        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]
        static extern bool QueryPerformanceFrequency(ref long count); 
        static void Main(string[] args)
        {
            long time1 = 0;
            long time2 = 0;
            long freq = 0;
            double res = 0;
            QueryPerformanceFrequency(ref freq);
            QueryPerformanceCounter(ref time1);
            int sum = 0;
            for (int i = 0; i < 1000; i++)
            {
                sum += 1;
            }
            QueryPerformanceCounter(ref time2);
            res = (double)(time2 - time1) / (double)freq;
            Console.WriteLine("程序耗时:{0}ms.", res.ToString("f10"));
            Console.ReadLine();
        }

运行结果:

 

参考文章:https://blog.csdn.net/xzjxylophone/article/details/6832160

 

 

 

 

你可能感兴趣的:(C#)