【发布时间】:2011-08-06 02:36:52
【问题描述】:
我正在编写一个程序来生成图形并检查它是否已连接。下面是代码。这是一些解释:我在平面上随机位置生成了许多点。然后我连接节点,而不是仅基于接近度。我的意思是说一个节点更有可能连接到更近的节点,这是由我在代码中使用的随机变量(h_sq)和距离决定的。因此,我生成所有链接(对称,即,如果我可以与 j 交谈,反之亦然),然后使用 BFS 检查图形是否已连接。
我的问题是代码似乎工作正常。但是,当节点数大于 ~2000 时,速度非常慢,我需要多次运行此函数以进行模拟。我什至尝试将其他库用于图形,但性能是相同的。
有谁知道我怎么可能加快一切?
谢谢,
int Graph::gen_links() {
if( save == true ) { // in case I want to store the structure of the graph
links.clear();
links.resize(xy.size());
}
double h_sq, d;
vector< vector<luint> > neighbors(xy.size());
// generate links
double tmp = snr_lin / gamma_0_lin;
// xy is a std vector of pairs containing the nodes' locations
for(luint i = 0; i < xy.size(); i++) {
for(luint j = i+1; j < xy.size(); j++) {
// generate |h|^2
d = distance(i, j);
if( d < d_crit ) // for sim purposes
d = 1.0;
h_sq = pow(mrand.randNorm(0, 1), 2.0) + pow(mrand.randNorm(0, 1), 2.0);
if( h_sq * tmp >= pow(d, alpha) ) {
// there exists a link between i and j
neighbors[i].push_back(j);
neighbors[j].push_back(i);
// options
if( save == true )
links.push_back( make_pair(i, j) );
}
}
if( neighbors[i].empty() && save == false ) {
// graph not connected. since save=false i dont need to store the structure,
// hence I exit
connected = 0;
return 1;
}
}
// here I do BFS to check whether the graph is connected or not, using neighbors
// BFS code...
return 1;
}
更新: 主要问题似乎是内部 for 循环中的 push_back 调用。在这种情况下,这是花费大部分时间的部分。我应该使用reserve() 来提高效率吗?
【问题讨论】:
标签: c++ performance graph simulation