[英]Eigen Matrix vs Numpy Array multiplication performance
我在这个问题中读到, eigen
具有非常好的性能。 但是,我试图比较eigen
MatrixXi
乘法速度与numpy
array
乘法。 并且numpy
表现更好(~26秒对比~29)。 有没有更有效的方法来做这个eigen
?
这是我的代码:
NumPy的:
import numpy as np
import time
n_a_rows = 4000
n_a_cols = 3000
n_b_rows = n_a_cols
n_b_cols = 200
a = np.arange(n_a_rows * n_a_cols).reshape(n_a_rows, n_a_cols)
b = np.arange(n_b_rows * n_b_cols).reshape(n_b_rows, n_b_cols)
start = time.time()
d = np.dot(a, b)
end = time.time()
print "time taken : {}".format(end - start)
结果:
time taken : 25.9291000366
征:
#include <iostream>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
int n_a_rows = 4000;
int n_a_cols = 3000;
int n_b_rows = n_a_cols;
int n_b_cols = 200;
MatrixXi a(n_a_rows, n_a_cols);
for (int i = 0; i < n_a_rows; ++ i)
for (int j = 0; j < n_a_cols; ++ j)
a (i, j) = n_a_cols * i + j;
MatrixXi b (n_b_rows, n_b_cols);
for (int i = 0; i < n_b_rows; ++ i)
for (int j = 0; j < n_b_cols; ++ j)
b (i, j) = n_b_cols * i + j;
MatrixXi d (n_a_rows, n_b_cols);
clock_t begin = clock();
d = a * b;
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "Time taken : " << elapsed_secs << std::endl;
}
结果:
Time taken : 29.05
我正在使用numpy 1.8.1
和eigen 3.2.0-4
。
更改:
a = np.arange(n_a_rows * n_a_cols).reshape(n_a_rows, n_a_cols)
b = np.arange(n_b_rows * n_b_cols).reshape(n_b_rows, n_b_cols)
成:
a = np.arange(n_a_rows * n_a_cols).reshape(n_a_rows, n_a_cols)*1.0
b = np.arange(n_b_rows * n_b_cols).reshape(n_b_rows, n_b_cols)*1.0
这至少在我的笔记本电脑上提供了100倍的提升:
time taken : 11.1231250763
VS:
time taken : 0.124922037125
除非你真的想要乘以整数。 在Eigen中,也可以更快地将双精度数乘以(相当于将MatrixXi替换为MatrixXd三次),但在那里我只看到1.5因子:所用时间:0.555005对比0.846788。
@Jitse Niesen和@ggael在评论中回答了我的问题。
我需要添加一个标志来在编译时打开优化: -O2 -DNDEBUG
(O是大写o,而不是零)。
在包含这个标志之后, eigen
代码在0.6
秒内运行而不是在没有它的情况下运行~29
秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.