c++ - 为什么填充我的 std::vector 的运行时间在 0 到 ~16 毫秒之间跳跃?

标签 c++ c++11 vector runtime

我的 C++ 应用程序的瓶颈是填充 std::vector< std::vector< Chunk >>。有时这需要 0 毫秒,有时需要 ~16 毫秒,它永远不会介于两者之间,比如 2-14 毫秒。为什么?我总是在 vector 中填充大约 5000 个元素。我的代码是:

block 结构:

struct Chunk {
    std::vector<std::pair<std::string, std::pair<int, int>>> chreatures_;
};

初始化:

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;

最佳答案

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

关于c++ - 为什么填充我的 std::vector 的运行时间在 0 到 ~16 毫秒之间跳跃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36202687/

相关文章:

c++ - 类型别名中的详细类型说明符

c++ - 为什么编译器不能像在变量声明中那样在结构成员中设置 char[] = { .. } 的大小?

c++ - 在 shared_ptr 上修改 std::less

c++ - 在大项目中使用 c++11 std::tuple

Matlab:如何根据索引向量将1填充到零向量?

r - 如何在向量序列中索引向量序列

c++ - C++ 元编程中的模板柯里化(Currying)

iphone - 在 iOS 中使用 C++ 和 cocos2d-x 在浏览器中打开 URL

c++ - 为什么这个缓冲区大小没有被套接字正确处理?

C++ 多类型映射,如 PHP stdClass