gpt4 book ai didi

c++ - 避免检查可能如果

转载 作者:行者123 更新时间:2023-11-30 05:21:20 25 4
gpt4 key购买 nike

鉴于以下情况:

class ReadWrite {
public:
int Read(size_t address);
void Write(size_t address, int val);
private:
std::map<size_t, int> db;
}

在读取函数中访问以前没有写入的地址时,我想抛出指定此类错误的异常或允许该错误并返回 0,换句话说,我想使用 std::map<size_t, int>::operator[]()std::map<size_t, int>::at() ,取决于用户可以设置的一些 bool 值。所以我添加以下内容:

class ReadWrite {
public:
int Read(size_t add) { if (allow) return db[add]; return db.at(add);}
void Write(size_t add, int val) { db[add] = val; }
void Allow() { allow = true; }
private:
bool allow = false;
std::map<size_t, int> db;
}

问题在于:通常,程序会在程序开始时调用一次 allow 或 none,然后再进行多次访问。因此,就性能而言,这段代码很糟糕,因为它每次都执行检查 if (allow)通常它总是为真或总是为假。那么你会如何解决这样的问题呢?

编辑:

虽然描述的这个类的用例(一开始是一个或没有 Allow())很可能是不确定的,所以我必须允许用户调用 Allow()动态地。

另一个编辑:

使用函数指针的解决方案:使用编译器无法内联的函数指针所带来的性能开销如何?如果我们使用 std::function相反,这会解决问题吗?

最佳答案

Usually, the program will have one call of allow or none at the beginning of the program and then afterwards many accesses. So, performance wise, this code is bad because it every-time performs the check if (allow) where usually it's either always true or always false. So how would you solve such problem?

我不会,CPU会。
Branch Prediction会发现答案很可能在很长一段时间内都是相同的,因此它将能够在硬件级别上非常优化分支。它仍然会产生一些开销,但可以忽略不计。

如果你真的需要优化你的程序,我认为你最好使用 std::unordered_map 而不是 std::map,或者转向一些更快的映射实现,像 google::dense_hash_map。与 map 查找相比,该分支微不足道。

关于c++ - 避免检查可能如果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com