不要手动StopWatch了,让BenchmarkDotNet帮你

Nuget: https://www.nuget.org/packages/BenchmarkDotNet/

Project Site: https://github.com/PerfDotNet/BenchmarkDotNet

clip_image002

使用非常方便。

第一步,创建待测试的类和方法,并用Benchmark属性修饰需要测试的方法。注意类和方法都必须是public的。

using BenchmarkDotNet;

namespace NumberRollOverTest
{
    public class NumberRollOver
    {
        public const byte Max = byte.MaxValue;

        [Benchmark]
        public void TestRollOver()
        {
            RollOver(Max);    
        }

        [Benchmark]
        public void TestRollOverByCast()
        {
            RollOverByCast(Max);    
        }
...
}

第二步,启动Benchmark主程序(BenchmarkRunner)

using System;

namespace NumberRollOverTest
{
    class Program
    {
        static void Main(string[] args)
        {
            new BenchmarkDotNet.BenchmarkRunner().RunCompetition(new NumberRollOver());

            Console.Read();
        }

        
    }
}
原文地址:https://www.cnblogs.com/rader/p/4920862.html