gpt4 book ai didi

python - Eigen 矩阵 vs Numpy 数组乘法性能

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:10 25 4
gpt4 key购买 nike

我读了in this question 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

Eigen :

#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.1eigen 3.2.0-4

最佳答案

@Jitse Niesen 和@ggael 在评论中回答了我的问题。

我需要在编译时添加一个标志来打开优化:-O2 -DNDEBUG(O 是大写的 o,不是零)。

包含此标志后,eigen 代码在 0.6 秒内运行,而没有它则为 ~29 秒。

关于python - Eigen 矩阵 vs Numpy 数组乘法性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24566920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com