我有一个包含以下两个班级成员的班级:
uint64_t m_numOfOperations; // how many times an operation was done
uint64_t m_someOtherMember; // will be divided by m_numOfOperations
在某些函数中, updateNumberOfOperations(),我将此计数器递增1并将m_someOtherMember除以计数器(m_numOfOperations)y,如下所示:
m_someOtherMember = m_someOtherMember / m_numOfOperation;
现在,此功能将被多次调用,最终将导致 numOfOperation 达到其最大值,然后在下次调用中达到零 - 此时会导致除以零的错误。
现在,我想以下直接实现将会解决这个问题,但是,每次UINT64_MAX次检查零都有点效率。
所以我的问题是 - 是否有更有效的方法来实现我的updateNumberOfOperations()方法的当前实现的功能?
谢谢, 盖伊。
我班级的当前实施:
#include <cstdint>
class MyClass
{
public:
void updateNumberOfOperations()
{
if (UINT64_MAX == m_numOfOperations)
{
++m_numOfOperations;
}
++m_numOfOperations;
m_someOtherMember = m_someOtherMember / m_numOfOperations;
}
private:
uint64_t m_numOfOperations; // how many times an operation was done
uint64_t m_someOtherMember; // will be divided by numOfOperations
};
答案 0 :(得分:7)
您可以使用以下函数递增无符号数,并在换行时跳过0值:
inline uint64_t inc(uint64_t a) {
++a; // Wrapping unsigned numbers is well-defined.
return a + !a;
}
It generates no branches in the code.
另请注意,如果您以纳秒为单位递增uint64_t
一次,则需要大约584年才能换行。