在 C# 中检查一段代码性能的正确方法

Correct way to check performance of piece of code in C#

假设我有两段代码,我想检查 CPU 这些代码的使用情况和内存并一起比较,这是检查性能的好方法吗:

public class CodeChecker: IDisposable
{


    public PerformanceResult Check(Action<int> codeToTest, int loopLength)
    {

        var stopWatch = new Stopwatch();

        stopWatch.Start();

        for(var i = 0; i < loopLength; i++)
        {
            codeToTest.Invoke(i);
        }

        stopWatch.Stop();
        var process = Process.GetCurrentProcess();

        var result = new PerformanceResult(stopWatch.ElapsedMilliseconds, process.PrivateMemorySize64);
        return result;

    }
}

public class PerformanceResult
{
    public long DurationMilliseconds { get; set; }
    public long PrivateMemoryBytes { get; set; }

    public PerformanceResult(long durationMilliseconds, long privateMemoryBytes)
    {
        DurationMilliseconds = durationMilliseconds;
        PrivateMemoryBytes = privateMemoryBytes;
    }


    public override string ToString()
    {
        return $"Duration: {DurationMilliseconds} - Memory: {PrivateMemoryBytes}";
    }
}

并且:

static void Main(string[] args)
{
    Console.WriteLine("Start!");
    int loopLength = 10000000;

    var collection = new Dictionary<int, Target>();


    PerformanceResult result;
    using (var codeChecker = new CodeChecker())
    {
        result = codeChecker.Check((int i) => collection.Add(i, new Target()) , loopLength);
    }

    Console.WriteLine($"Dict Performance: {result}");


    var list = new List<Target>();
    using(var codeChecker = new CodeChecker())
    {
        result = codeChecker.Check((int i) => list.Add(new Target()), loopLength);
    }

    Console.WriteLine($"List Performance: {result}");
    Console.ReadLine();
}

我正在寻找以编程方式检查性能的方法,我想检查一段代码,而不是所有应用程序。

有什么改进上述代码的建议吗?

我会接受任何使用免费工具的建议。

有很多因素可能会对您的测量造成偏差,包括 CLR 和 JIT 编译器的影响、堆状态、冷或热 运行、系统的整体负载等。理想情况下,您需要隔离您希望相互进行基准测试以排除相互影响的代码片段,仅对热 运行 进行基准测试,不进行冷基准测试以排除 JIT 编译和其他冷 运行 因素以及您需要的最重要的因素执行多个 运行 以获取统计信息,因为单个 运行 可能不具有代表性,尤其是在意味着多任务处理的系统上。幸运的是,您不必手动完成所有操作 - 基准测试有很好的 library,它可以完成所有提到的事情以及更多,并且广泛用于各种 .NET 项目。