[英]Optimizing C++ Vector for Search
在我目前的項目中,我盡力堅持過早優化是萬惡之源的原則。 不過,現在代碼已經測試過了,是時候進行優化了。 我做了一些分析,結果發現我的代碼花費了將近 20% 的時間在一個函數中,它找到所有可能的孩子,把它們放在一個向量中,然后返回它們。 請注意,我正在優化速度,內存限制不是一個因素。
現在這個函數看起來像這樣:
void Board::GetBoardChildren(std::vector<Board> &children)
{
children.reserve(open_columns_.size()); // only reserve max number of children
UpdateOpenColumns();
for (auto i : open_columns_)
{
short position_adding_to = ColumnToPosition(i);
MakeMove(position_adding_to); // make the possible move
children.push_back(*this); // add to vector of children
ReverseMove(); // undo move
}
}
根據分析,我的代碼在children.push_back(*this);
行上花費了大約 40% 的時間children.push_back(*this);
我這樣調用函數:
std::vector<Board> current_children;
current_state.GetBoardChildren(current_children);
我在想,由於可能的最大孩子數很小(7),只使用數組會更好嗎? 或者我不能做很多事情來優化這個功能?
從你對我的評論的回應來看,很可能大部分時間都花在了抄板上
children.push_back(*this);
您需要找到一種避免制作所有這些副本的方法,或者一種使它們更便宜的方法。
簡單地將向量更改為數組或列表可能不會對性能產生任何影響。
最重要的問題是:你真的需要 current_state 中的所有狀態嗎? 如果您只是按照默認順序迭代它們一兩次,那么就不需要向量,只需根據需要生成它們。
如果你真的需要它,這是下一步。 由於Board
的復制成本很高,因此只跟蹤DifferenceBoard
可能會更好。 偽代碼:
struct DifferenceBoard { // or maybe inherit from Board that a DifferenceBoard
// can be built from another DifferenceBoard
Board *original;
int fromposition, toposition;
State state_at_position;
State get(int y, int x) const {
if ((x,y) == fromposition) return Empty;
if ((x,y) == toposition ) return state_at_position;
return original->get();
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.