【发布时间】:2021-07-30 13:08:28
【问题描述】:
我有一个圆列表(中心和半径),对于每个圆,我需要对所有圆心在圆内的圆做一些处理。
我做了一个简单的双循环
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Points
{
double x;
double y;
double r;
} Points;
int main()
{
int num = 10000; // number of circles
Points c[num]; // circles
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
// checking if the distance of point i and j is small than i's radius
if (c[i].r > sqrt(pow(c[i].x - c[j].x, 2) + pow(c[i].y - c[j].y, 2)))
{
// do the processing
}
}
}
return 0;
}
问题在于性能。对于 10,000 个圆圈,我进行 100M 次迭代。
【问题讨论】:
-
一方面,您可以在外循环中计算
pow(c[i].r, 2),并在内循环中跳过sqrt() -
根据数据,可能值得使用曼哈顿或切比雪夫距离排除候选人
-
然后你可以在你的内部 (j) 循环中检查'内在性'。您只需要计算一次距离,然后进行两次比较(每个半径一个)。
-
感觉应该可以进行更多根本性的改进......
-
根据圆圈的密集程度,按
x坐标排序可能让您只检查几个相邻条目(那些在当前中心的r内具有x坐标的条目)。