【发布时间】:2015-08-04 08:13:22
【问题描述】:
我使用 unordered_map 作为稀疏 3D 数组 (128 x 128 x 128) 将值插入到网格中,前提是网格单元仍然空闲。
到目前为止,我总是使用 find() 检查单元格是否空闲,如果是,那么我使用 insert() 或 emplace() 添加了一个元素。 现在我发现我可以使用 insert 和 emplace 的返回值来检查元素是否已添加,或者地图中是否已经存在具有相同键的元素。我认为这可以提高性能,因为我可以完全删除 find 的使用。
事实证明,不是通过插入而不查找来提高性能,而是性能实际上下降了,我不知道为什么。
我已将我的应用程序简化为这个示例,其中点是随机生成的,然后插入到网格中。
#include <unordered_map>
#include <random>
#include <chrono>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <string>
using std::cout;
using std::endl;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
using std::chrono::duration_cast;
using std::unordered_map;
int num_elements = 5'000'000;
void findThenInsert(){
cout << endl << "find and emplace" << endl;
auto start = high_resolution_clock::now();
std::mt19937 gen(123);
std::uniform_real_distribution<> dis(0, 128);
unordered_map<int, int> grid;
int count = 0;
for(int i = 0; i < num_elements; i++){
float x = dis(gen);
float y = dis(gen);
float z = (cos(x*0.1) * sin(x*0.1) + 1.0) * 64.0;
int index = int(x) + int(y) * 128 + int(z) * 128 * 128;
auto it = grid.find(index);
if(it == grid.end()){
grid.emplace(index, count);
count++;
}
}
cout << "elements: " << count << endl;
cout << "load factor: " << grid.load_factor() << endl;
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end - start).count();
float seconds = duration / 1000.0f;
cout << seconds << "s" << endl;
}
void insertThenCheckForSuccess(){
cout << endl << "emplace and check success" << endl;
auto start = high_resolution_clock::now();
std::mt19937 gen(123);
std::uniform_real_distribution<> dis(0, 128);
unordered_map<int, int> grid;
int count = 0;
for(int i = 0; i < num_elements; i++){
float x = dis(gen);
float y = dis(gen);
float z = (cos(x*0.1) * sin(x*0.1) + 1.0) * 64.0;
int index = int(x) + int(y) * 128 + int(z) * 128 * 128;
auto it = grid.emplace(index, count);
if(it.second){
count++;
}
}
cout << "elements: " << count << endl;
cout << "load factor: " << grid.load_factor() << endl;
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end - start).count();
float seconds = duration / 1000.0f;
cout << seconds << "s" << endl;
}
int main(){
findThenInsert();
insertThenCheckForSuccess();
}
在这两种情况下,地图的大小都是 82901,所以我假设结果完全相同。
查找并放置:0.937s 就位然后检查:1.268s【问题讨论】:
-
-
@TheParamagneticCroissant is C++14:“可选的单引号(')可以插入数字之间作为分隔符,编译器会忽略它们。”
-
@ChrisDrew 哦,这很好,没有意识到这一点。
-
@T.C.为什么需要分配?
-
@n.m emplace 需要
Args&&... args你需要用这些参数构造一些东西,然后才能将它与其他键进行比较,据我所知,emplace 的常见实现将在所需的目标中构造(动态分配在内存)并在不需要时将其删除。