这个方法效果很好。但是我想知道是否有其他方法可以使这个方法更精确,我的最终目标是将同一个方法运行10次,并得到它的平均执行时间。
public static void Measure(Action action, int noOfTimesToRunThisMethod)
{
long averageTime = 0;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Started");
for (int i = 1; i <= noOfTimesToRunThisMethod; i++)
{
Stopwatch watch = Stopwatch.StartNew();
action();
watch.Stop();
Console.WriteLine($"Attempt:{i.ToString("D2")} Time Taken:{watch.ElapsedMilliseconds} ms");
averageTime += watch.ElapsedMilliseconds;
}
Console.WriteLine($"Average: {averageTime/ noOfTimesToRunThisMethod}");
}
使用这个辅助方法
var noOfTimesToRunThisMethod = 10;
Utils.Measure(() =>
{
MyMethod(arr)
},noOfTimesToRunThisMethod);
您可以使用Benchmark来测试您的执行方法时间。有一个Benchmark的例子:
public class Program
{
public static void Main()
{
BenchmarkRunner.Run<ListMemoryAllocationTest>();
}
}
[MemoryDiagnoser]
public class ListMemoryAllocationTest
{
public int Count { get; set; } = 900000;
[Benchmark]
public void DefaultConstructor()
{
List<int> numbers = new List<int>();
for (int i = 0; i < Count; i++)
{
numbers.Add(i);
}
}
[Benchmark]
public void AddCountToConstructor()
{
List<int> secondNumbers = new List<int>(Count);
for (int i = 0; i < Count; i++)
{
secondNumbers.Add(i);
}
}
}
将项目配置从Build
更改为Release
并运行project.
结果:
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
| DefaultConstructor | 753.4 us | 14.80 us | 15.20 us | 628.9063 | 627.9297 | 237.3047 | 1,024 KB |
| AddCountToConstructor | 499.6 us | 9.86 us | 17.78 us | 255.8594 | 255.8594 | 95.7031 | 391 KB |