C# 计算量大,如何让它更快
我知道这是一个愚蠢的问题,为什么这个代码 minX 的计算成本很高,但我想,有人可能会告诉我我的错误。谢谢
// getMap is a 2 dimentional array of type short I need to find maxX,minX,maxY,minY
//Can't use Math.Min , as it will get the lower bound i.e 0, i want values after filtering
for (int X = 0; X < getMap.GetLength(0); X++)
{
for (int Y = 0; Y < getMap.GetLength(1); Y++)
{
if((short)getMap.GetValue(X,Y) != 0)
{
//if i take it out, it works fine ,I need to
if (minX > X )
minX = X;
else
X = minX;
// Prints some stuff and does other computation
}
}
}
// Draws image
I know its a dumb question to ask about , why this code minX is computationally expensive, but i thought, someone might inform me of my mistake. Thanks
// getMap is a 2 dimentional array of type short I need to find maxX,minX,maxY,minY
//Can't use Math.Min , as it will get the lower bound i.e 0, i want values after filtering
for (int X = 0; X < getMap.GetLength(0); X++)
{
for (int Y = 0; Y < getMap.GetLength(1); Y++)
{
if((short)getMap.GetValue(X,Y) != 0)
{
//if i take it out, it works fine ,I need to
if (minX > X )
minX = X;
else
X = minX;
// Prints some stuff and does other computation
}
}
}
// Draws image
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
else X = minX;
部分没有多大意义。它可能会导致无限循环,因为您将循环变量X
设置为较低的值。仅当最多 1 列包含非零值时,您的代码才会终止(假设您将 minX 初始化为一个大值)。
例如,假设
X=0
和X=1
列在某处都包含非零值。然后,当它达到 0 列中的非零值时,minX
设置为 0。然后,它通过X=1
达到非零值,注意到minX> ;X
为 false,并将 X 设置回 0。并永远重复。the
else X = minX;
part doesn't make much sense. It can cause an endless loop because you're setting back the loop variableX
to a lower value.Your code will only terminate if at most 1 column contains a non zero value(assuming you initialized minX to a large value).
For example assume that both the
X=0
and theX=1
column contain a non zero value somewhere. Then when it hits the non zero value in the 0 columnminX
is set to 0. Then later it hits the non zero value withX=1
notices thatminX>X
is false and sets X back to 0. And repeat forever.我不知道
(short)getMap.GetValue(X,Y)
与getmap[X,Y]
相比如何,但似乎过于复杂。您可以做的是将
short[,] getMap
替换为short[][] getMap
。在这些嵌套循环场景中,数组的数组(锯齿状数组)通常更快,因为抖动可以更好地优化范围检查。
I don't know how
(short)getMap.GetValue(X,Y)
compares to justgetmap[X,Y]
but is seems over-complicated.What you can do is to replace
short[,] getMap
withshort[][] getMap
.Array-of-array (jagged arrays) are ususally faster in these nested loop scenarios because the Jitter can optimize range checking better.