我的c ++应用程序的瓶颈是填充std :: vector<的std ::矢量<块>取代。有时这需要0毫秒,有时需要16毫秒,它之间不会有任何东西,比如2-14毫秒。为什么?我总是在向量中填充大约5000个元素。我的代码是:
块结构:
struct Chunk {
std::vector<std::pair<std::string, std::pair<int, int>>> chreatures_;
};
INIT:
int height_ = 100;
int width_ = 100;
const int chunksidelength_ = 10;
std::vector<std::vector<Chunk>> chunks_;
std::list<std::shared_ptr<Creature>> creatures_;
chunks_.reserve(height_ / chunksidelength_);
for (int i = 0; i < height_ / chunksidelength_; i++) {
chunks_.emplace_back();
chunks_[i].reserve(width_ / chunksidelength_);
for (int j = 0; j < width_ / chunksidelength_; j++) {
chunks_[i].emplace_back();
chunks_[i][j].chreatures_.
reserve(chunksidelength_ * chunksidelength_ * 3);
}
}
填充:
long long before = (std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::system_clock::now().time_since_epoch())).count();
for (std::vector<Chunk>& chunks : chunks_) {
for (Chunk& chunk : chunks) {
chunk.chreatures_.clear();
}
}
for (const std::shared_ptr<Creature>& creature : creatures_) {
int x = creature->x() / chunksidelength_;
int y = creature->y() / chunksidelength_;
std::string image = creature->image_path();
std::pair<int, int> position(creature->x(), creature->y());
chunks_[y][x].chreatures_.emplace_back(std::make_pair(image, position));
}
long long after = (std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::system_clock::now().time_since_epoch())).count();
std::cout << after - before << std::endl;