A用Python编写的程序的速度有问题。这个程序是“磁场中铁磁性粒子的模拟”,更具体地说是在磁性惰性液体中。该程序运行,但与C++编写的相同程序相比非常缓慢,但我在Python上编写了一个研究项目。在
总的来说,程序代码是基于循环的,有很多浮点运算。有一个随机数目的粒子(随机产生的位置)在磁场的影响下相互作用。在
这是初始位置:
http://i.stack.imgur.com/T15Bb.jpg
最后:
http://i.stack.imgur.com/0nU5D.jpg
主回路(在对称.py,用k变量)迭代是时间步,是计算粒子在时间点上的坐标以及作用在它上的力(吸引力和一个小的斥力)。为了加快速度,我想用并行处理同时计算迭代次数,但这是不可能的,因为一次迭代的计算依赖于前一次迭代的计算。在
我不知道Python比C++慢得多。作为一个例子,计算了529个粒子在一个时间步长内的模拟(在我的计算机上):
C++~0.5秒
Python~50年代
那么,如何加快项目进度呢?请帮忙。在
This code is only calculate, not drawing particles as in the pictures. The number of simulate partcile is on SymConst.py, this is nrH*nrL.
在对称.py在
#coding:windows-1250
from os import system
from SymCalc import *
from SymParticle import *
if __name__ == '__main__':
App = SymCalc()
App.MainLoop()
在SymParticle.py在
^{pr2}$在SymParticle.py在
#coding:windows-1250
class Particle(object):
# generating a particle properties
def __init__(self, num, x, y, fx, fy, frx, fry, nx, ny, ddx, ddy, r):
self.num = num
self.x = x
self.y = y
self.fx = fx
self.fy = fy
self.frx = frx
self.fry = fry
self.nx = nx
self.ny = ny
self.ddx = ddx
self.ddy = ddy
self.r = r
在符号Const.py在
#coding:windows-1250
### Constant
M_H0 = 3e4
MI_0 = 12.56e-7
MI_P = 2000
eta = 0.1
k0 = 10001
dt = 1e-6 # time step
H0 = 5.95e-4
L0 = 5.95e-4
nrH = 4
nrL = 4
Constant = 100
nParticle = nrH*nrL # number of particle
使用PyPy!在
要调查此问题,首先使用PythoncProfile模块来分析代码并找出所有时间都在哪里使用(print语句被注释掉):
在您的例子中,大部分时间都花在
^{pr2}$SymCalc.py:62(ParticleCalculate)
函数中。看看这个函数,它似乎主要是内存访问和计算。这是一个查看PyPy的好例子!在1.071s-好多了!与系统上的原始执行时间进行比较:
相关问题 更多 >
编程相关推荐