我编写了一个Fortran函数,该函数以一种非常简单的方式来计算一维数字数组的移动平均值:
function moving_average(data, w)
implicit none
integer, intent(in) :: w
real(8), intent(in) :: data(:)
integer :: n, i
real(8) :: moving_average(size(data)-w+1)
n = w-1
do i=1, size(data)-n
moving_average(i) = mean(data(i:i+n))
end do
end function
Run Code Online (Sandbox Code Playgroud)
该函数mean定义为:
real(8) function mean(data)
implicit none
real(8), dimension(:), intent(in) :: data
mean = sum(data)/size(data)
end function
Run Code Online (Sandbox Code Playgroud)
在moving_average具有100000个数字的数据集和1000的窗口宽度的笔记本电脑上运行该功能时,需要0.1秒。但是,该函数running_mean在这个岗位使用numpy只需要1毫秒。为什么我的算法这么慢?