对于一个小程序,python和fortran差异的巨大差异

jha*_*ade 0 python fortran

我正在读取包含512**3数据点的单精度数据的文件.基于一个阈值,我为每个点分配一个1或0的标志.我写了两个程序做同样的事情,一个在fortran,另一个在python中.但是fortran中的那个需要0.1秒,而python中的那个需要几分钟.这是正常的吗?或者你能指出我的python程序的问题:

fortran.f

  program vorticity_tracking

  implicit none

  integer, parameter :: length = 512**3
  integer, parameter :: threshold = 1320.0

  character(255) :: filen
  real, dimension(length) :: stored_data
  integer, dimension(length) :: flag
  integer index

  filen = "vor.dat"

  print *, "Reading the file ", trim(filen)
  open(10, file=trim(filen),form="unformatted",
 &     access="direct", recl = length*4)
  read (10, rec=1) stored_data
  close(10)

  do index = 1, length
     if (stored_data(index).ge.threshold) then
        flag(index) = 1
     else
        flag(index) = 0
     end if
  end do

  stop
  end program
Run Code Online (Sandbox Code Playgroud)

Python文件:

#!/usr/bin/env python

import struct
import numpy as np

f_type = 'float32'
length = 512**3
threshold = 1320.0
file = 'vor_00000_455.float'

f = open(file,'rb')
data = np.fromfile(f, dtype=f_type, count=-1)
f.close()

flag = []

for index in range(length):
    if (data[index] >= threshold):
        flag.append(1)
    else:
        flag.append(0)
Run Code Online (Sandbox Code Playgroud)

********* 编辑 ******

感谢您的意见.我不确定如何在fortran中这样做.我试过以下但这仍然很慢.

 flag = np.ndarray(length, dtype=np.bool)    
 for index in range(length):
     if (data[index] >= threshold):
         flag[index] = 1
     else:
         flag[index] = 0
Run Code Online (Sandbox Code Playgroud)

有人可以给我看看吗?

Dav*_*rtz 6

你的两个程序是完全不同的.您的Python代码会反复更改结构的大小.您的Fortran代码没有.你没有比较两种语言,你比较两种算法,其中一种显然是劣等的.