我有一个程序,看起来像这样:设计模式和“分支预测”
struct EventTypeA {
int someInt; // random between 0 and 9
};
struct EventTypeB {
int someOtherInt; // random between 0 and 100000
};
int EventAHandler(EventTypeA e) {
// Updates multiplier
static int multipler = e.someInt;
return multiplier;
}
double EventBHandler(EventTypeB e) {
/* This is a simple example for illustration, the actual intermediate
calculation takes up much more computational time than this */
int intermediateResult = (e.someOtherInt * multipler) % 10 + 1;
if (intermediateResult <= 3) { DoAction1(); }
if (intermediateResult >= 7) { DoAction2(); }
}
...
...
void SomeMethodWithinSomeClass() {
while (true) {
// Listen for events of type A and B
// if EventTypeA occurs, invoke EventAHandler
// if EventTypeB occurs, invoke EventBHandler
}
}
我想有EventAHandler
预先计算的intermediateResult
的查找表来查找所有可能的EventTypeB.someOtherInt
' s分别是一个EventTypeA
到达,我有一个新的multiplier
时间,所以我可以用查找替换EventBHandler
的intermediateResult
计算。
这样做的原因是,我EventBHandler
是时间敏感,而EventAHandler
是不是:所以当一个EventTypeB
后到达,EventBHandler
不必执行int intermediateResult = (e.someOtherInt * multipler) % 10 + 1;
(我们假设这种说法占用了更多的时钟周期)和只需要查找。
我的问题是,如果EventTypeA
频繁发生,而EventTypeB
很少发生,它只会表现良好。
在发生几个连续的EventTypeB
的情况下,比我可以预先计算查找表的速度快,我想要提前终止预计算并切换回原始方法。有没有一种干净的方式来做到这一点?
我一声给予好评的聪明的数学运算,而不是最终的答案,我虽然期待,因为实际的中间计算比这个(类似多次调用线性代数库和大型矩阵操作)更计算昂贵。这是我的错,因为我没有澄清,所以我会更新这个问题。谢谢! – elleciel