似乎每次我运行性能测试时,在时间稳定之前的前几次迭代中总是有一个“放松”时间。
这是性能测试代码(在这种情况下,我正在测试 Lambda 和 LINQ 之间的差异):
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Sandbox
{
public class Program
{
private static long sum = 0;
private static int count = 0;
public class Item
{
public string name;
public int id;
}
public static void Main(string[] args)
{
// START TESTING PARAMETERS
List<Item> items = new List<Item>();
for (int i = 0; i < 1000; i++)
{
items.Add(new Item
{
id = i,
name = "name_" + i.ToString()
});
}
// END TESTING PARAMETERS
Stopwatch sw = new Stopwatch();
sw.Start();
for (int j = 0; j < 10; j++)
{
for (int i = 0; i < 5000; i++)
{
// START TESTING CODE
Item itm = items.Find(x => x.name == "name_" + i.ToString());
// END TESTING CODE
}
sum += sw.ElapsedMilliseconds;
count++;
sw.Restart();
Console.WriteLine("Average: {0}", sum / count);
}
}
}
}
以下是 100,000 次测试运行 5 次迭代的平均结果:
Average: 1023 Average: 1079 Average: 1017 Average: 1147 Average: 1054
Average: 1003 Average: 963 Average: 1001 Average: 1007 Average: 1020
Average: 1009 Average: 926 Average: 951 Average: 958 Average: 966
Average: 972 Average: 908 Average: 927 Average: 934 Average: 936
Average: 946 Average: 896 Average: 922 Average: 919 Average: 918
Average: 931 Average: 889 Average: 926 Average: 910 Average: 907
Average: 919 Average: 883 Average: 916 Average: 903 Average: 899
Average: 911 Average: 880 Average: 908 Average: 898 Average: 893
Average: 904 Average: 877 Average: 902 Average: 894 Average: 899
Average: 899 Average: 874 Average: 909 Average: 891 Average: 894
Average: 895 Average: 873 Average: 926 Average: 889 Average: 890
Average: 898 Average: 871 Average: 937 Average: 886 Average: 887
Average: 898 Average: 869 Average: 944 Average: 884 Average: 907
Average: 894 Average: 868 Average: 938 Average: 882 Average: 921
Average: 891 Average: 868 Average: 934 Average: 881 Average: 923
Average: 889 Average: 867 Average: 929 Average: 880 Average: 919
Average: 887 Average: 866 Average: 925 Average: 884 Average: 916
Average: 885 Average: 866 Average: 931 Average: 892 Average: 912
Average: 889 Average: 865 Average: 927 Average: 902 Average: 909
Average: 891 Average: 870 Average: 924 Average: 907 Average: 917
为什么每次我进行测试时都有一个缓冲期?