计算代码运行时间

在优化代码过程中,有时需要统计一些代码的运行时间。
在 C# 中有几种方式可以用来统计代码的运行时间,如:DateTimeStopwatch,一般推荐使用Stopwatch,其精度较高,但无论哪种方式都会有一定的误差存在。

1、 Stopwatch

using System;
using System.Threading;
using System.Diagnostics; // Used for: Stopwatch

namespace BaseTmpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw01 = new Stopwatch();
            sw01.Start();
            DoSomething();
            sw01.Stop();

            Console.WriteLine($"Elapsed Time = {sw01.ElapsedMilliseconds} ms");
            Console.ReadKey();
        }

        // 需要被统计运行时间的代码
        static void DoSomething()
        {
            Thread.Sleep(1000);
        }
    }
}

2、DateTime

using System;
using System.Threading;

namespace BaseTmpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;
            DoSomething();
            DateTime endTime = DateTime.Now;
            double elapsedTime = (endTime - startTime).TotalMilliseconds;
            Console.WriteLine($"Elapsed Time = {elapsedTime} ms");

            Console.ReadKey();
        }
        static void DoSomething()
        {
            Thread.Sleep(1000);
        }
    }
}


【参考资料】

  1. Calculate the execution time of a method
  2. Is DateTime.Now the best way to measure a function's performance?
  3. Measure execution time in C#
posted @ 2022-08-05 18:04  Jeffxue  阅读(58)  评论(0编辑  收藏  举报