【问题标题】:Calling a function makes my code ridiculousy slow调用函数让我的代码慢得离谱
【发布时间】:2013-03-02 21:13:22
【问题描述】:

我正在尝试实现一种算法,给定一个矩形和用户决定的多个多边形,可以识别它们是在矩形内部、外部还是与矩形相交,并提供所述多边形的数量。

我编写了一个算法并且它可以工作,但我注意到在编译之后至少需要 20 秒才能启动(如果我第二次、第三次或任何其他时间启动它就不会发生这种情况)。

试图弄清楚是什么让我的代码如此缓慢,我注意到如果我删除对确定多边形相对于矩形位置的函数的调用,程序会立即运行。

我试图找出错误但什么也没找到

在这里

// struct used in the function
struct Polygon
{
    int ** points;
    int vertices;
};
// inside, outside and over are the number of polygons that are inside, outside or intersect the rectangle,
// they're initialized to 0 in the main.
// down_side, up_side are the y_coordinate of the two horizontals sides.
// left_side, right_side are the x_coordinate of the two vertical sides.
void checkPolygons( Polygon * polygon, int & inside, int & outside, int & over, unsigned int polygons, const unsigned int down_side, const unsigned int up_side, const unsigned int left_side, const unsigned int right_side )
{
    for ( unsigned int pol = 0; pol < polygons; ++pol )
    {
        unsigned int insideVertices = 0;
        unsigned int vertices = polygon[ pol ].vertices;

        for ( unsigned int point = 0; point < vertices; ++point )
        {
            unsigned int x_coordinate = polygon[ pol ].points[ point ][ 0 ];
            unsigned int y_coordinate = polygon[ pol ].points[ point ][ 1 ];

            if ( ( x_coordinate <= right_side ) and ( x_coordinate >= left_side ) and ( y_coordinate <= up_side ) and ( y_coordinate >= down_side ) )
            {
                insideVertices++;
            }

        }

        if ( insideVertices == 0 )
            ++outside;
        else if ( insideVertices == vertices ) 
            ++inside;
        else
            ++over;
    }
}

【问题讨论】:

  • 你使用的是什么编译器/操作系统?
  • Windows下MinGW(gcc)
  • 也许是 codereview.stackexchange.com? unsigned int x_coordinate = polygon[ pol ].points[ point ][ 0 ]; 看起来是缓存的杀手。
  • 我可能错了,但由于一些非常奇怪的网络相关问题,mingw 编译的代码在某些 Windows 系统上加载缓慢。尝试禁用您的网络适配器,让我们知道会发生什么,或者尝试不同的编译器/操作系统...我遇到了这个问题,只禁用无线和有线网络使程序加载速度更快。
  • 另一种可能性是您的防病毒软件正在检查新编译的可执行文件。

标签: c++ performance function call


【解决方案1】:

检查您的防病毒活动和配置。它可能正在扫描新编译的可执行文件以查找病毒。如果是这种情况,您可能希望从病毒扫描中排除您正在编译的目录。

【讨论】:

  • 太棒了……当现实生活侵入程序员所钻研的抽象领域时
  • @fritzone 发生在我身上好几次了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2014-09-05
  • 2013-03-23
  • 1970-01-01
相关资源
最近更新 更多