游戏编程精粹(一) 模板元降低数学方法时间复杂度

1.模板元可以作为虚拟编译程序,快速大量的创建优化的代码。

2.任何数学算法都能被模板化,只要有好的编译程序,中间可以完全优化掉,已达到最高的效率

例子1:斐波那契序列:0,1,1,2,3,5,8,13... 通用方程为 Fib(n) = Fib(n-1) + Fib(n-2)

通用函数:

unsigned RecursiveFib(unsigned n)
{
    if (n <= 1)
        return n;
    
    return RecursiveFib(n - 1) + RecursiveFib(n - 2);
}

使用模板:

template<unsigned N> 
struct Fib
{
    enum
    {
        Val = Fib<N - 1>::Val + Fib<N - 2>::Val
    };
};

template<> struct Fib<0> { enum { Val = 0 }; };
template<> struct Fib<1> { enum { Val = 1 }; };

#define FibT(n) Fib<n>::Val
然后比较时间:
#include <iostream>
#include <time.h>

template<typename T>
void FunctionTime(T p)
{
    clock_t cStartTime = clock();
    p();
    clock_t cEndTime = clock();
    std::cout << "Running time: " << static_cast<double>(cEndTime - cStartTime) << std::endl;
}

void GetFib1()
{
    RecursiveFib(30);
}

void GetFib2()
{
    FibT(30);
}

int main()
{
    FunctionTime(*GetFib1);
    FunctionTime(*GetFib2);
    
    return 0;
}

所以到底做了什么优化呢?

模板因为在编译期间确定参数,所以编译期间就可以将过程优化掉 => 动态分类 1.运行期多态 2.编译期多态,编译期多态指的就是模板。


猜你喜欢

转载自blog.csdn.net/weixin_42561030/article/details/80833575