C# 计算量大,如何让它更快

发布于 2024-11-03 10:07:49 字数 693 浏览 0 评论 0原文

我知道这是一个愚蠢的问题,为什么这个代码 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悟红尘 2024-11-10 10:07:49

else X = minX; 部分没有多大意义。它可能会导致无限循环,因为您将循环变量 X 设置为较低的值。

仅当最多 1 列包含非零值时,您的代码才会终止(假设您将 minX 初始化为一个大值)。

例如,假设 X=0X=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 variable X 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 the X=1 column contain a non zero value somewhere. Then when it hits the non zero value in the 0 column minX is set to 0. Then later it hits the non zero value with X=1 notices that minX>X is false and sets X back to 0. And repeat forever.

云胡 2024-11-10 10:07:49

我不知道 (short)getMap.GetValue(X,Y)getmap[X,Y] 相比如何,但似乎过于复杂。

您可以做的是将 short[,] getMap 替换为 short[][] getMap

在这些嵌套循环场景中,数组的数组(锯齿状数组)通常更快,因为抖动可以更好地优化范围检查。

I don't know how (short)getMap.GetValue(X,Y) compares to just getmap[X,Y] but is seems over-complicated.

What you can do is to replace short[,] getMap with short[][] getMap.

Array-of-array (jagged arrays) are ususally faster in these nested loop scenarios because the Jitter can optimize range checking better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文