更新:我的同事Terry告诉我有一种矩阵运算的方式计算斐波那契数列,更适于并行。他还提供了利用TBB的parallel_reduce模板计算斐波那契数列的代码(在TBB示例代码的基础上修改得来,比原始代码更加简洁易懂)。实验结果表明,这种方法在计算的斐波那契数列足够长时,可以提高性能。
矩阵方式计算斐波那契数列的原理:
代码:
#include <tbb/task_scheduler_init.h> #include <tbb/blocked_range.h> #include <tbb/parallel_reduce.h> #include <tbb/tick_count.h> #include <stdio.h> using namespace std; using namespace tbb; //! Matrix 2x2 class struct Matrix2x2 { //! Array of unsigned ints unsigned int v[2][2]; Matrix2x2() {} Matrix2x2(unsigned int v00, unsigned int v01, unsigned int v10, unsigned int v11) { v[0][0] = v00; v[0][1] = v01; v[1][0] = v10; v[1][1] = v11; } Matrix2x2 operator * (const Matrix2x2 &to) const; //< Multiply two Matrices }; //! matrix to be multiplied static const Matrix2x2 Matrix1110(1, 1, 1, 0); //! Identify matrix to be served as the base of the product static