我正在用Python编写一个科学应用程序,其核心是一个处理器密集型的循环。我希望尽可能地优化这一点,将给最终用户带来的不便降到最低,他们可能会将其作为Python脚本的未编译集合,并将使用Windows、Mac和(主要是Ubuntu)Linux。在
它目前是用Python编写的,带有少量NumPy,我已经包含了下面的代码。在是否有一个不需要编译的快速解决方案?这似乎是保持平台独立性的最简单方法。在
如果使用像Pyrex这样需要编译的东西,有没有一种简单的方法可以捆绑许多模块,并让Python根据检测到的OS和Python版本在它们之间进行选择?有没有一种简单的方法来构建模块集合,而不需要访问每一个Python版本的每个系统?在
是否有一种方法特别适合于多处理器优化?在
(如果你感兴趣的话,这个循环是通过把附近大量磁性离子的贡献加在一起来计算晶体内某个给定点的磁场,这些离子被视为微小的条形磁铁。基本上是these的一个巨大的和。)# calculate_dipole
# -------------------------
# calculate_dipole works out the dipole field at a given point within the crystal unit cell
# ---
# INPUT
# mu = position at which to calculate the dipole field
# r_i = array of atomic positions
# mom_i = corresponding array of magnetic moments
# ---
# OUTPUT
# B = the B-field at this point
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i
r_unit = unit_vectors(relative)
#4pi / mu0 (at the front of the dipole eqn)
A = 1e-7
#initalise dipole field
B = zeros(3,float)
for i in range(len(relative)):
#work out the dipole field and add it to the estimate so far
B += A*(3*dot(mom_i[i],r_unit[i])*r_unit[i] - mom_i[i]) / sqrt(dot(relative[i],relative[i]))**3
return B