gpt4 book ai didi

python - 有没有办法提高在 Windows 下使用 Fortran 中数组的速度,比如 Python numpy?

转载 作者:行者123 更新时间:2023-12-03 21:58:07 26 4
gpt4 key购买 nike

很抱歉可能的重复。
关于问题。
与Windows下的GNU Fortran(9.2.0 MinGW.org GCC Build-20200227-1)相比,python 3.8.2中的numpy(1.18.2)为矩阵产品提供了非常高的模拟速度(快3倍)。我使用了命令 gfortran.exe test.f没有任何额外的选择。
有谁知道是什么导致了这种情况,是否可以提高 Fortran 中的模拟速度?
这是fortran代码:

program product_test
INTEGER :: N,N_count,i,j,k,nc
REAL*8 :: t1,t2
REAL*8,dimension (:,:), allocatable :: a,b,c

N = 200
N_count = 10

allocate ( a(N,N) )
allocate ( b(N,N) )
allocate ( c(N,N) )

call RANDOM_NUMBER(a)
call RANDOM_NUMBER(b)

print *, 'Matrix Multiplication: C = A * B for size (',N,',',N,')'
call CPU_TIME ( time_begin )
do nc=1,N_count
c = MATMUL(a,b)
end do
call CPU_TIME ( time_end )
t2 = (time_end - time_begin)/N_count
print *, 'Time of operation was ', t2, ' seconds'

end
这是输出:

Matrix Multiplication: C = A * B for size ( 200 , 200 )
Time of operation was 9.3749E-003 seconds


这是python 3代码:
import numpy as np
import time

N = 200
N_count = 10

a = np.random.rand(N,N)
b = np.random.rand(N,N)
c = np.zeros([N,N], dtype = float)


print('Matrix product in python (using numpy): c= a*b for size (',N,',',N,')')
start_time = time.time()
for nc in range(N_count):
c = a@b
t2 = (time.time() - start_time)/N_count
print('Elapsed time = ',t2,'s')
这是输出:

Matrix product in python (using numpy): c= a*b for size ( 200 , 200 )
Elapsed time = 0.0031252 s



**附加测试。**根据“roygvib”和“Vladimir F”的评论,我已经用blas/lapack进行了测试: gfortran test.f -lopenblas -o test.exegfortran test.f -ffast-math -o test.exegfortran test.f -lblas -o test.exegfortran test.f -llapack -o test.exe给我 的计算时间0.0063s 用于大小为 ( 200 x 200 ) 的方阵的矩阵乘法。
不幸的是,我删除了以前版本的 mingw,新的测试是在 GNU Fortran 下执行的(x86_64-posix-seh-rev0,由 MinGW-W64 项目 8.1.0 构建)。可能是我做错了什么,因为 -llapack 之间没有区别, -lblas , -lopenblas .对于时间测量,我使用了 SYSTEM_CLOCK正如“弗拉基米尔 F”所建议的那样。
现在,它更好了,但 numpy 仍然比 fortran 快(不是三倍而是两倍)。
跟随“Vladimir F”的最后一条评论,我发现与Python不同,Fortran主要使用一个逻辑核心(我的PC上有4个逻辑核心,带有intel i3 CPU)。因此,这是我的PC(Windows8.1)上未正确配置MinGW的问题。
enter image description here

最佳答案

使用 MATMUL或外部库,如 BLAS对于 Fortran 中的矩阵乘法,我们有很多关于矩阵乘法性能的问题

Fortran matrix multiplication performance in different optimization
performance of fortran matrix operations
How does BLAS get such extreme performance?

你应该先阅读它们。你永远不应该在一个简单的 for 循环中进行矩阵乘法,这总是很慢。矩阵乘法有特殊的算法。它们以有效的方式使用内存带宽,并使用矢量化指令(通常直接用汇编编写)。

许多 Fortran 编译器将允许您直接通过 MATMUL 调用 BLAS xGEMM。在 gfortran 中可以使用 -fexternal-blas roygvib 提到的。如果您对此有疑问,请直接调用 DGEMM。

某些 BLAS 实现能够使用多个线程。如果你尝试,你 绝不能使用 CPU_TIME 来测量速度,您必须使用 SYSTEM_CLOCK 或替代方法。

此外,您没有报告使用任何优化标志,如 -O3 .除非优化的外部库完成所有工作,否则这些对于任何体面的性能都是必要的。

关于python - 有没有办法提高在 Windows 下使用 Fortran 中数组的速度,比如 Python numpy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61089510/

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