zoukankan      html  css  js  c++  java
  • 拒绝switch,程序加速之函数指针数组

    先看一个使用switch语句的程序:

    #include <stdio.h>
    #include <time.h>
    
    //加法
    int add(int a,int b)
    {
    	return a+b;
    }
    
    //减法
    int subtract(int a,int b)
    {
    	return a-b;
    }
    
    //乘法
    int multi(int a,int b)
    {
    	return a*b;
    }
    
    //除法
    int divide(int a,int b)
    {
    	return a/b;
    }
    
    int claculate(int a,int b,char oper)
    {
    	//这里使用switch语句
    	switch (oper)
    	{
    	case '+':
    		return add(a,b);
    	case '-':
    		return subtract(a,b);
    	case '*':
    		return multi(a,b);
    	case '/':
    		return divide(a,b);
    	default:
    		return -1;
    		break;
    	}
    }
    
    
    void main()
    {
    	int a = 250;
    	int b = 5;
    	//统计程序执行时间
    	clock_t start, finish; 
    	start = clock();
    	printf("%d
    ",claculate(a,b,'+'));
    	printf("%d
    ",claculate(a,b,'-'));
    	printf("%d
    ",claculate(a,b,'*'));
    	printf("%d
    ",claculate(a,b,'/'));
    	finish = clock();
    	printf( "%f seconds
    ", (double)(finish - start) / CLOCKS_PER_SEC );  
    }
    
    再看一个使用函数指针数组的程序
    #include <stdio.h>
    #include <time.h>
    
    //加法
    int add(int a,int b)
    {
    	return a+b;
    }
    
    //减法
    int subtract(int a,int b)
    {
    	return a-b;
    }
    
    //乘法
    int multi(int a,int b)
    {
    	return a*b;
    }
    
    //除法
    int divide(int a,int b)
    {
    	return a/b;
    }
    
    
    
    int claculate(int a,int b,int oper)
    {
    	//事实上这里应该使用hashMap。将字符'+'映射到add函数。

    //直接使用数字是为了简便 //声明指向函数指针的数组 int (*pfunc[])(int a,int b) = {add,subtract,multi,divide}; return pfunc[oper](a,b); } void main() { int a = 250; int b = 5; //统计程序执行时间 clock_t start, finish; start = clock(); printf("%d ",claculate(a,b,0)); printf("%d ",claculate(a,b,1)); printf("%d ",claculate(a,b,2)); printf("%d ",claculate(a,b,3)); finish = clock(); printf( "%f seconds ", (double)(finish - start) / CLOCKS_PER_SEC ); }


    当switch推断语句中case的个数不多时,上面两个程序几乎相同。但假设case非常多时,使用函数指针数组要快非常多。

    类似地。在Java里面也能够使用反射来代替swith语句产生类似的效果。


  • 相关阅读:
    HFUT 1356.转啊转(安徽省2016“京胜杯”程序设计大赛 E)
    HFUT 1354.砝码称重(安徽省2016“京胜杯”程序设计大赛 A)
    AOJ 331.汉诺塔
    AOJ 763.过河卒
    AOJ 762.分数数列
    AOJ 761.Fibonacci序列
    AOJ 760.尾数相等的数
    POJ 1035.Spell checker
    POJ 2299.Ultra-QuickSort
    POJ 2503.Babelfish
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7093325.html
Copyright © 2011-2022 走看看