I would like to replace a sequence of matrices in my code with a single 3-D Eigen::Tensor. With this in mind, I try to compare Tensor and Matrix performances.
Function "tensorContractTest" below performs a contraction of (n,n,n) rank 3 tensor with a rank 1 tensor of size n (n = 500). This contraction computes n**2 dot products, so in terms of the number of operations, it is equivalent to multiplication of two (n,n) matrices (function "matrixProductTest" below).
When run on Visual Studio 2013, function "tensorContractTest" runs ~ 40 times slower than "matrixProductTest". Probably, I am missing something. Help is appreciated.
#include <unsupported/Eigen/CXX11/Tensor>
using namespace Eigen;
// Contracts 3-dimensional (n x n x n) tensor with 1-dimensional (n) tensor.
// By the number of operations, it's equivalent to multiplication of
// two (n, n) matrices (matrixProdTest).
Tensor<double, 2> tensorContractTest(int n)
{
Tensor<double, 3> a(n, n, n); a.setConstant(1.);
Tensor<double, 1> b(n); b.setConstant(1.);
auto indexPair = array<IndexPair<int>, 1>{IndexPair<int>(2,0)};
Tensor<double, 2> result = a.contract(b, indexPair);
return result;
}
MatrixXd matrixProductTest(int n)
{
MatrixXd a = MatrixXd::Ones(n, n), result = a * a;
return result;
}