概述
在C/C++嵌入式系统编程这一书中,优化的代码这十章节中提到过 “提高代码的效率”,在此做个笔录,个人理解有限能免会有出现错误,各位看官,如有发现错误地方请指出谢谢!一起学习,一起讨论,共同进步!
进入正题,直接贴代码。(注:这里并没有做过多的测试,只是看到了提到这样的方法,做个笔录而已。)感兴趣的攻城狮们自行验证测试哈。^_^ !!
查询表
switch 语句是一个普通的编程技术,使用时需要注意。每一个由机器语言实现的测试和跳转仅仅是为了决定下一步要做什么工作,就把宝贵的处理器时间耗尽了。为了提高速度,设法把具体的情况按照它们发生的相对频率排序。换
句话说,把最可能发生的情况放在第一,最不可能的情况放在最后。这样会减少平均的执行时间,但是在最差情况下根本没有改善。如果每一个情况下都有许多的工作要做, 那么也许把整个 switch 语句用一个指向函数指针的表替换含更加有效。比如,下面的程序段是一个待改善的候选对象:
enum NodeType {NodeA, NodeB, NodeC}
switch(getNodeType())
{
case NodeA:
...
case NodeB:
...
case NodeC:
...
}
引用书中的原话:为了提高速度,我们要用下面的代码替换这个 switch 语句。这段代码的第一部分是准备工作:一个函数指针数组的创建。第二部分是用更有效的一行语句替换 switch 语句。
int status = 0;
enum NodeType {NodeA, NodeB, NodeC, Node_SUM};
int processNodeA(void);
int processNodeB(void);
int processNodeC(void);
int getNodeType(int index)
{
return index;
}
int processNodeA(void)
{
return NodeA;
}
int processNodeB(void)
{
return NodeB;
}
int processNodeC(void)
{
return NodeC;
}
/*
* Establishment of a table of pointers to functions.
*/
int (* nodeFunctions[])() = { processNodeA, processNodeB, processNodeC };
/*
* The entire switch statement is replaced by the next line.
*/
void testFunction(void)
{
static int i = 0;
#if 0
do{
switch (getNodeType(i)) {
case NodeA:
status = NodeA;
break;
case NodeB:
status = NodeB;
break;
case NodeC:
status = NodeC;
break;
default:
break;
}
printf("status, %d\n", status);
//}while(++i < Node_SUM);
}while(i++ < 2);
#else
for (int i = 0; i < Node_SUM; ++i) {
status = nodeFunctions[getNodeType(i)]();
printf("status, %d\n", status);
}
#endif
}
int main() {
testFunction();
}
运行结果:
总结:只是做个笔录,方便以后查阅。
更多推荐
C语言简单的编程技术(代码优化)
发布评论