我試圖實現一個給定矩形和由用戶決定的多個多邊形的算法,它可以識別它們是在裏面,外面還是相交矩形,並提供所述多邊形。我編碼算法,它的工作原理,但我注意到編譯後,它至少需要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;
}
}
你在用什麼編譯器/操作系統? – fritzone 2013-03-02 21:15:46
在Windows下的MinGW(gcc) – doplumi 2013-03-02 21:17:55
也許codereview.stackexchange.com? 'unsigned int x_coordinate = polygon [pol] .points [point] [0];'看起來像是殺手級的緩存。 – 2013-03-02 21:17:56