Skip to content

Instantly share code, notes, and snippets.

@jeremytrimble
Last active June 6, 2016 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremytrimble/2be79f0203f295b515ae4578ea956ebc to your computer and use it in GitHub Desktop.
Save jeremytrimble/2be79f0203f295b515ae4578ea956ebc to your computer and use it in GitHub Desktop.
Eigen performance with different expressions of the same computation.
// Compile with: g++ -I/usr/include/eigen3 -std=c++11 -O3 t.cpp -o t
#include <Eigen/Dense>
#include <chrono>
#include <iostream>
#include <cmath>
using Eigen::MatrixXcf;
using Eigen::MatrixXf;
const int NUM_TIMES=1000;
using ArrayXf = Eigen::Array <float, Eigen::Dynamic, Eigen::Dynamic>;
using ArrayXcf = Eigen::Array <std::complex<float>, Eigen::Dynamic, Eigen::Dynamic>;
float test1( const MatrixXcf & mat )
{
ArrayXcf arr = mat.array();
ArrayXcf conj = arr.conjugate();
ArrayXcf magc = arr * conj;
ArrayXf mag = magc.real();
return mag.sum();
}
float test2( const MatrixXcf & mat )
{
return ( mat.array() * mat.array().conjugate() ).real().sum();
}
float test3( const MatrixXcf & mat )
{
ArrayXcf magc = ( mat.array() * mat.array().conjugate() );
ArrayXf mag = magc.real();
return mag.sum();
}
int main(int argc, char *argv[])
{
uint64_t test1_us =0, test2_us =0;
uint64_t test3_us =0;
MatrixXcf m(8*1024, 4);
float res1, res2, res3;
for (int i = 0; i < NUM_TIMES; ++i) {
m.setRandom();
{
auto tick = std::chrono::steady_clock::now();
res1 = test1(m);
auto tock = std::chrono::steady_clock::now();
test1_us += (std::chrono::duration_cast<std::chrono::microseconds>(tock-tick)).count();
}
{
auto tick = std::chrono::steady_clock::now();
res2 = test2(m);
auto tock = std::chrono::steady_clock::now();
test2_us += (std::chrono::duration_cast<std::chrono::microseconds>(tock-tick)).count();
}
{
auto tick = std::chrono::steady_clock::now();
res3 = test3(m);
auto tock = std::chrono::steady_clock::now();
test3_us += (std::chrono::duration_cast<std::chrono::microseconds>(tock-tick)).count();
}
if ( abs(res1 - res2) > 1e-10 )
throw std::runtime_error("Tests give inconsistent results");
if ( abs(res3 - res2) > 1e-10 )
throw std::runtime_error("Tests give inconsistent results");
}
std::cout
<< "test1_us: " << test1_us << std::endl
<< "test2_us: " << test2_us << std::endl
<< "test3_us: " << test3_us << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment