我有500000个随机生成的Tuple<long,long,string>
对象的列表,在这些对象上执行简单的“之间”搜索:
var data = new List<Tuple<long,long,string>>(500000);
...
var cnt = data.Count(t => t.Item1 <= x && t.Item2 >= x);
当我生成随机数组并为100个随机生成的值运行搜索时x
,搜索将在大约四秒钟内完成。知道排序确实会对搜索产生很大的影响,但是,我决定在运行100次搜索之前先对数据进行排序Item1
,然后再按,再按Item2
,最后按Item3
- 进行排序。由于分支预测,我希望排序后的版本执行得更快:我的想法是,一旦到达Item1 == x
,所有进一步的检查t.Item1 <= x
都会正确地预测分支为“ no take”,从而加快分支的尾部。搜索。令我惊讶的是,在排序数组上进行搜索的时间是原来的两倍!
我尝试切换实验顺序,并为随机数生成器使用了不同的种子,但是效果是一样的:在未排序的数组中搜索的速度几乎是在同一数组中搜索速度的两倍,但是排序!
有谁能很好地解释这种奇怪的影响?我测试的源代码如下;我正在使用.NET 4.0。
private const int TotalCount = 500000;
private const int TotalQueries = 100;
private static long NextLong(Random r) {
var data = new byte[8];
r.NextBytes(data);
return BitConverter.ToInt64(data, 0);
}
private class TupleComparer : IComparer<Tuple<long,long,string>> {
public int Compare(Tuple<long,long,string> x, Tuple<long,long,string> y) {
var res = x.Item1.CompareTo(y.Item1);
if (res != 0) return res;
res = x.Item2.CompareTo(y.Item2);
return (res != 0) ? res : String.CompareOrdinal(x.Item3, y.Item3);
}
}
static void Test(bool doSort) {
var data = new List<Tuple<long,long,string>>(TotalCount);
var random = new Random(1000000007);
var sw = new Stopwatch();
sw.Start();
for (var i = 0 ; i != TotalCount ; i++) {
var a = NextLong(random);
var b = NextLong(random);
if (a > b) {
var tmp = a;
a = b;
b = tmp;
}
var s = string.Format("{0}-{1}", a, b);
data.Add(Tuple.Create(a, b, s));
}
sw.Stop();
if (doSort) {
data.Sort(new TupleComparer());
}
Console.WriteLine("Populated in {0}", sw.Elapsed);
sw.Reset();
var total = 0L;
sw.Start();
for (var i = 0 ; i != TotalQueries ; i++) {
var x = NextLong(random);
var cnt = data.Count(t => t.Item1 <= x && t.Item2 >= x);
total += cnt;
}
sw.Stop();
Console.WriteLine("Found {0} matches in {1} ({2})", total, sw.Elapsed, doSort ? "Sorted" : "Unsorted");
}
static void Main() {
Test(false);
Test(true);
Test(false);
Test(true);
}
Populated in 00:00:01.3176257
Found 15614281 matches in 00:00:04.2463478 (Unsorted)
Populated in 00:00:01.3345087
Found 15614281 matches in 00:00:08.5393730 (Sorted)
Populated in 00:00:01.3665681
Found 15614281 matches in 00:00:04.1796578 (Unsorted)
Populated in 00:00:01.3326378
Found 15614281 matches in 00:00:08.6027886 (Sorted)
Item1 == x
,所有进一步的检查t.Item1 <= x
将正确地将该分支预测为“ no take”,从而加快了搜索的尾部。显然,严酷的现实证明了这种想法是错误的:)