为什么填充我的std :: vector的运行时间在0到~16ms之间跳转?

时间:2016-03-24 14:32:20

标签: c++ c++11 vector runtime

我的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;

1 个答案:

答案 0 :(得分:1)

你在Windows上吗?定时器分辨率为15.6 ms吗?这可能意味着您的代码只是'执行得非常快',在0或1个计时器滴答中。