c函数的性能提示



查找有关如何加速/重写以下函数的提示。数组是有序的,所以我想可以用BinarySearch代替它,但由于我需要返回最近的索引,这可能不合适。

为了进行本次调查,假设istart=0,iend=阵列长度-1

/// <summary>
/// Given an array "xx" of length "n", and given a value "x", this routine
/// returns a value "j" such that "x" is between xx(j) and xx(j+1).  
/// xx must be monotonic, either increasing or decreasing.  j=istart or j=n is
/// returned to indicate that x is out of range.
/// Modified to set the start and end points by "istart" and "iend" 
/// </summary>
public static int Locate(double[] xx, int n, int istart, int iend, double x)
{
if (istart > iend || x < xx[istart])
{
return istart;
}
else if (x > xx[iend])
{
return iend;
}
int mid;
while (istart +1 < iend)
{
mid = (istart + iend) >> 1;

if (x < xx[mid])
{
iend = mid ;
}
else
{
istart = mid ;
}
}
if (iend >= n || xx[iend] != x)
{
return iend -1;
}
else 
return iend;

}

请参阅Array.BinarySearch

如果找到值,则指定数组中指定值的索引;否则为负数。如果找不到值,并且值小于数组中的一个或多个元素,则返回的负数是大于值的第一个元素的索引的逐位补码。如果找不到值,并且值大于数组中的所有元素,则返回的负数是(最后一个元素的索引加1(的按位补码。如果使用未排序的数组调用此方法,则返回值可能不正确,并且可能返回负数,即使数组中存在值。

所以你应该能够用替换你的功能

var index = Array.BinarySearch(xx, istart, iend - istart + 1, x);
if(index < 0){
index = ~index -1 // take the bitwise complement and subtract one to get the index of the value before x

请注意,您可能需要对空数组之类的情况进行一些额外的检查,或者x是否小于或大于所有值,因为这类情况似乎需要一些特定的输出。

使得";x〃;介于xx(j(和xx(j+1(之间

此处的"between"有点不明确,因为它没有指定范围是否包含。你必须假设它是包容性的,因为x不会是非包容性集合x到x+n的一部分。

还要注意,参数有点奇怪,不需要长度,因为数组知道自己的长度。在指定数组的间隔时,通常使用index+length,而不是start+end,因为是否应该包含结束索引可能会有一些混淆。

最后一点是,无论何时处理性能,都要衡量。Benchmark.net是黄金标准,但在紧要关头,秒表可能会起作用。探查器也有助于提示问题可能在哪里

最新更新