加快一个长python代码的速度,因为只有一个块,所以速度很慢

Speed up a long python code that proves to be slow only due to a single block

本文关键字:速度 因为 有一个 一个 代码 python      更新时间:2023-10-16

我们有一个巨大的空间,里面充满了许多粒子(~10^8(,这些粒子具有已知的质量阵列("HI_mass"(、三维位置("HI_position"(和一些有趣的分数("HI_fraction"(。该体积中还有一些具有不同但已知质量阵列("mass_data"(、位置("position_data"(和大小("radius_data"(的假想球体(~10^3(。

我们想把每个假想球体中的所有气体粒子(对气体质量的贡献很小(加起来,得出上面提到的每个假想球体的"气体质量"。一旦我们得到了每个球体的质量,我们就计算出一个称为"sigma_HI"的量。如果这个量高于某个阈值,那么我们将以{id:mass}字典的形式跟踪该球体的单个质量,以便以后用于进一步的计算。第三个块需要很长时间才能在整个代码的上下文中运行,而整个代码很长,而且不包括在内;我只复制了代码中被证明很慢的那部分。

import numpy as np
enclosing_circles_gas = {}
#info of imaginary spheres where *_data are stored arrays based on some random (otherwise positive integer) ids
for id, position, radius, mass zip(id_data, position_data, radius_data, mass_data):  
if (mass >= low_mass_cutoff):
for i in np.where(HI_fraction > 0):                            # HI_fraction is a 1d array
gas_mass = 0
if (np.linalg.norm(HI_position[i] - position) <= radius):  # HI_position and position: 3d array of particles and single sphere vector
gas_mass += HI_mass[i]*HI_fraction[i]                  # HI_mass and HI_fraction are 1d arrays of particles and their fractions
if (gas_mass/mass >= 1.0e-6):
enclosing_circles_gas[id] = float('{:.4f}'.format(mass))

我的问题是:如何使用C++在python中转换这个非常慢的块以加快整个代码的速度?

我尝试过的事情:将嵌套循环更改为列表理解(但这仍然很慢(

if (mass >= low_mass_cutoff):
gas_mass = sum( HI_mass[i]*HI_fraction[i] for i in np.where(HI_fraction > 0)[0] if (np.linalg.norm(HI_position[i] - position) <= radius))
if (gas_mass/mass >= 1.0e-6):
enclosing_circles_gas[id] = float('{:.4f}'.format(mass))

您应该找到一种方法来记录循环各个部分的时间。但是,如果是字符串到双精度到字符串的转换,那么以下从数字中截断数字而不是正确取整的方法呢?

import math
def trunc_digits(x, digits):
d = math.log10(abs(x)) - digits
d = int(math.ceil(d))
d = math.pow(10, d)
m = math.fmod(x, d)
x = x - m
return x
x = 9.87654321e-6
print (x, "->", trunc_digits(x, 4))
y = 9.87654321e6
print (y, "->", trunc_digits(y, 4))
a = -1.87654321e-6
print (a, "->", trunc_digits(a, 4))
b = -1.87654321e6
print (b, "->", trunc_digits(b, 4))