[英]Why does this noexcept matters for performance so much while a similar other noexcept does not?
我有一段通用代码,其性能对我来说很重要,因为我被要求匹配一个用C
编写的著名手工代码的运行时间。 在我开始玩noexcept
之前,我的代码运行了4.8秒 。 通过将所有可能想到的地方都noexcept
地方(我知道这不是一个好主意,但出于学习目的,我还是这么做了),代码加速了3.3秒。 然后我开始恢复的变更,直到我得到了更好的性能(3.1秒 ),并保持与单 noexcept
!
问题是:为什么这个noexcept
这么大的帮助? 这里是:
static const AllActions& allActions_() noexcept {
static const AllActions instance = computeAllActions();
return instance;
}
有趣的是,我还有另一个类似的功能,没有noexcept
就很好(即,将noexcept
放在那不会提高性能):
static const AllMDDeltas& mdDeltas_() {
static const AllMDDeltas instance = computeAllMDDeltas();
return instance;
}
我的代码(执行递归深度优先搜索)多次调用这两个函数,因此第二个函数对整体性能的重要性与第一个函数相同。
PS这是用于更多上下文的周围代码(引用的函数和它们调用的函数在清单的末尾):
/// The sliding-tile puzzle domain.
/// \tparam nRows Number of rows on the board.
/// \tparam nRows Number of columns on the board.
template <int nRows, int nColumns>
struct SlidingTile : core::sb::DomainBase {
/// The type representing the cost of actions in the domain. Every
/// domain must provide this name.
using CostType = int;
using SNeighbor =
core::sb::StateNeighbor<SlidingTile>; ///< State neighbor type.
using ANeighbor =
core::sb::ActionNeighbor<SlidingTile>; ///< Action neighbor type.
/// The type for representing an action. The position of the tile being moved.
using Action = int;
/// Number of positions.
static constexpr int size_ = nRows * nColumns;
/// The type for the vector of actions for a given position of the blank.
using BlankActions = std::vector<ANeighbor>;
/// The type for all the actions in the domain.
using AllActions = std::array<BlankActions, size_>;
/// The type for two-dimension array of Manhattan distance heuristic deltas
/// for a given tile. The indexes are from and to of an action.
using TileMDDeltas = std::array<std::array<int, size_>, size_>;
/// The type for all Manhattan distance heuristic deltas.
using AllMDDeltas = std::array<TileMDDeltas, size_>;
/// The type for raw state representation.
using Board = std::array<int, size_>;
/// Initializes the ordered state.
SlidingTile() {
int i = -1;
for (auto &el : tiles_) el = ++i;
}
/// Initializes the state from a string, e.g. "[1, 4, 2, 3, 0, 5]" or "1 4 2
/// 4 0 5" for 3x2 board.
/// \param s The string.
SlidingTile(const std::string &s) {
int i = -1;
for (auto el : core::util::split(s, {' ', ',', '[', ']'})) {
tiles_[++i] = std::stoi(el);
if (tiles_[i] == 0) blank_ = i;
}
}
/// The default copy constructor.
SlidingTile(const SlidingTile &) = default;
/// The default assignment operator.
/// \return Reference to the assigned state.
SlidingTile &operator=(const SlidingTile &) = default;
/// Returns the array of tiles at each position.
/// \return The raw representation of the state, which is the array of tiles
/// at each position..
const Board &getTiles() const { return tiles_; }
/// Applies an action to the state.
/// \param a The action to be applied, i.e. the next position of the blank
/// on the board.
/// \return The state after the action.
SlidingTile &apply(Action a) {
tiles_[blank_] = tiles_[a];
blank_ = a;
return *this;
}
/// Returns the reverse of the given action in this state.
/// \param a The action whose reverse is to be returned.
/// \return The reverse of the given action.
Action reverseAction(Action a) const {
(void)a;
return blank_;
}
/// Computes the state neighbors of the state.
/// \return Vector of state neighbors of the state.
std::vector<SNeighbor> stateSuccessors() const {
std::vector<SNeighbor> res;
for (auto a : actionSuccessors()) {
auto n = SlidingTile{*this}.apply(a.action());
res.push_back(std::move(n));
}
return res;
}
/// Computes the action neighbors of the state.
/// \return Vector of action neighbors of the state.
const std::vector<ANeighbor> &actionSuccessors() const {
return allActions_()[blank_];
}
/// The change in the Manhattan distance heuristic to the goal state with
/// ordered tiles and the blank at position 0 due to applying the given action.
/// \param a The given action.
/// \return The change in the Manhattan distance heuristic to the goal state
/// with ordered pancake due to applying the given action.
int mdDelta(Action a) const {
return mdDeltas_()[tiles_[a]][a][blank_];
}
/// Computes the Manhattan distance heuristic to the goal state with
/// ordered tiles and the blank at position 0.
/// \return The Manhattan distance heuristic to the goal state with
/// ordered tiles and the blank at position 0.
int mdHeuristic() const {
int res = 0;
for (int pos = 0; pos < size_; ++pos)
if (pos != blank_)
res += rowDist(pos, tiles_[pos]) + colDist(pos, tiles_[pos]);
return res;
}
/// Computes the hash-code of the state.
/// \return The hash-code of the state.
std::size_t hash() const {
boost::hash<Board> v_hash;
return v_hash(tiles_);
}
/// Dumps the state to the given stream.
/// \tparam The stream type.
/// \param o The stream.
/// \return The modified stream.
template <class Stream> Stream &dump(Stream &o) const {
return o << tiles_;
}
/// Randomly shuffles the tiles.
void shuffle() {
auto old = tiles_;
while (old == tiles_)
std::random_shuffle(tiles_.begin(), tiles_.end());
}
/// The equality operator.
/// \param rhs The right-hand side of the operator.
/// \return \c true if the two states compare equal and \c false
/// otherwise.
bool operator==(const SlidingTile &rhs) const {
if (blank_ != rhs.blank_) return false;
for (int i = 0; i < size_; ++i)
if (i != blank_ && tiles_[i] != rhs.tiles_[i]) return false;
return true;
}
/// Returns a random state.
/// \return A random state.
static SlidingTile random() {
SlidingTile res{};
res.shuffle();
return res;
}
private:
/// Tile at each position. This does not include the position of the blank,
/// which is stored separately.
std::array<int, size_> tiles_;
/// Blank position.
int blank_{};
/// Computes the row number corresponding to the given position.
/// \return The row number corresponding to the given position.
static int row(int pos) { return pos / nColumns; }
/// The difference between the row numbers corresponding to the two given
/// positions.
/// \return The difference between the row numbers corresponding to the two
/// given positions.
static int rowDiff(int pos1, int pos2) { return row(pos1) - row(pos2); }
/// The distance between the row numbers corresponding to the two given
/// positions.
/// \return The distance between the row numbers corresponding to the two
/// given positions.
static int rowDist(int pos1, int pos2) {
return std::abs(rowDiff(pos1, pos2));
}
/// Computes the column number corresponding to the given position.
/// \return The column number corresponding to the given position.
static int col(int pos) { return pos % nColumns; }
/// The difference between the column numbers corresponding to the two given
/// positions.
/// \return The difference between the column numbers corresponding to the
/// two given positions.
static int colDiff(int pos1, int pos2) { return col(pos1) - col(pos2); }
/// The distance between the column numbers corresponding to the two given
/// positions.
/// \return The distance between the column numbers corresponding to the
/// two given positions.
static int colDist(int pos1, int pos2) {
return std::abs(colDiff(pos1, pos2));
}
/// Computes the actions available for each position of the blank.
static AllActions computeAllActions() {
AllActions res;
for (int blank = 0; blank < size_; ++blank) {
// the order is compatible with the code of Richard Korf.
if (blank > nColumns - 1)
res[blank].push_back(Action{blank - nColumns});
if (blank % nColumns > 0)
res[blank].push_back(Action{blank - 1});
if (blank % nColumns < nColumns - 1)
res[blank].push_back(Action{blank + 1});
if (blank < size_ - nColumns)
res[blank].push_back(Action{blank + nColumns});
}
return res;
}
/// Computes the heuristic updates for all the possible moves.
/// \return The heuristic updates for all the possible moves.
static AllMDDeltas computeAllMDDeltas() {
AllMDDeltas res;
for (int tile = 1; tile < size_; ++tile) {
for (int blank = 0; blank < size_; ++blank) {
for (const ANeighbor &a: allActions_()[blank]) {
int from = a.action(), to = blank;
res[tile][from][to] =
(rowDist(tile, to) - rowDist(tile, from)) +
(colDist(tile, to) - colDist(tile, from));
}
}
}
return res;
}
/// Returns all the actions.
/// \note See http://stackoverflow.com/a/42208278/2725810
static const AllActions& allActions_() noexcept {
static const AllActions instance = computeAllActions();
return instance;
}
/// Returns all the updates of the MD heuristic.
static const AllMDDeltas& mdDeltas_() {
static const AllMDDeltas instance = computeAllMDDeltas();
return instance;
}
};
与computeAllMDDeltas
不同,函数computeAllActions
包含一些对push_back
调用,这些调用可以执行一些内存分配。 如果基础分配器有异常,例如内存不足,则可能会抛出此异常。 这是编译器无法优化的,因为它取决于运行时参数。
添加noexcept
告诉编译器不会发生这些错误,这使他可以省略代码以进行异常处理。
看一下有关异常开销的讨论: C ++中的异常真的很慢吗
您可以轻松理解为什么使用noexcept可使代码更快,因为编译器不需要为您对push_back的每次调用创建处理程序列表。 您的函数computeAllActions包含了对可抛出函数的大多数调用,这就是为什么它使优化得到最大利用的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.