【问题标题】:Correct way to check performance of piece of code in C#在 C# 中检查代码段性能的正确方法
【发布时间】:2019-04-18 14:38:01
【问题描述】:

假设我有两段代码,我想检查这些代码的 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();
}

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

有任何改进上述代码的建议吗?

我愿意接受任何关于使用免费工具的建议。

【问题讨论】:

    标签: c# performance memory cpu-usage


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2018-09-25
      相关资源
      最近更新 更多