假设我有两段代码,我想检查这些代码的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项目。