有关提高这段python代码的计算速度的任何建议吗?

时间:2018-04-21 03:08:22

标签: python arrays numpy

我有一段python代码:

def ExtendedF(frequency):
    return 1/(1+frequency)

def frequency_critical(gamma, B, alpha):
    return 3 *gamma**2*B*sin(alpha)

def single_spectrum(frequency, gamma, B, alpha):
    freq_c = frequency_critical(gamma, B, alpha)     
    return B*ExtendedF(frequency/freq_c)

def spectra(number_bin, B_field, frequency_bin, energy_bin, alpha_bin):
    #length of number_bin, B_field, alpha_bin is the same
    Spectras = []
    for i in range(len(B_field)):
      Spectra = []
      current_B = B_field[i]
      current_number = number_bin[i] #array of certain length = len
      current_alpha = alpha_bins[i]
      for j in range(len(frequency_bins)):
         single_spectrum = single_spectrum(frequency_bins[j], 
                            energy_bins, current_B, current_alpha)
         Spectra.append(simps(single_spectrum * 
                   append(current_number, array([0])), energy_bins))
      Spectras.append(Spectra)
    return Spectras

由于B_field的长度非常大,因此这部分代码非常慢,很可能是由于使用了两个for循环。我是否有任何关于如何使这段代码更快的想法。我假设numpy数组操作会很有用,但我不确定如何实现它。

1 个答案:

答案 0 :(得分:0)

首先,您不需要在内循环中计算frequency_critical,因为与它相关的变量在内循环中不会改变。 此外,您可能会因预先为SpectrasSpectra分配内存而受益,因为它们的大小已知。 最后,您可以使用列表推导,这可能会给您带来一些性能提升(但并不重要)。像这样:

def spectra(number_bin, B_field, frequency_bin, energy_bin, alpha_bin):
    #length of number_bin, B_field, alpha_bin is the same
    Spectras = []
    for i in range(len(B_field)):
        current_number = number_bin[i]
        freq_c = 3*energy_bins**2*B_field[i]*sin(alpha_bins[i])
        Spectra = list(B_field[i] * ExtendedF(freq_j/freq_c) for freq_j in frequency_bins)
        Spectras.append(Spectra)
    return Spectras

当然这条线似乎不完整,所以我不能把它包含在我的答案中:

     Spectra.append(simps(single_spectrum * 
               append(current_number, array([0])), energy_bins))