我需要从双精度数组中找到n个最低值(不是0)(让我们调用数组样本).我需要在循环中多次执行此操作,因此执行速度至关重要.我尝试首先对数组进行排序,然后获取前10个值(不是0),但是,虽然说Array.Sort很快,但它成了瓶颈:
const int numLowestSamples = 10;
double[] samples;
double[] lowestSamples = new double[numLowestSamples];
for (int count = 0; count < iterations; count++) // iterations typically around 2600000
{
samples = whatever;
Array.Sort(samples);
lowestSamples = samples.SkipWhile(x => x == 0).Take(numLowestSamples).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
因此,我尝试了一个不同但不太干净的解决方案,首先读取前n个值,对它们进行排序,然后循环遍历样本中的所有其他值,检查该值是否小于已排序的lowestSamples数组中的最后一个值.如果该值较低,则将其替换为数组中的值,然后再次对数组进行排序.结果大约快了5倍:
const int numLowestSamples = 10;
double[] samples;
List<double> lowestSamples = new List<double>();
for (int count = 0; count < iterations; count++) // iterations typically around 2600000
{
samples = whatever;
lowestSamples.Clear();
// Read …Run Code Online (Sandbox Code Playgroud)