[英]Shared memory n-body simulation in Chapel
我的建议是使用(+) 减少意图对forces
在FORALL环,这将给每个任务的自己的私人副本forces
,然后(总和)减少他们的个人副本回原forces
的任务完全变。 这可以通过将以下with-clause附加到forall循环来完成:
forall q in 0..#n_bodies with (+ reduce forces) {
在这里,我寻找其他方法使代码更优雅,并建议从这个问题的2D数组更改为数组的数组,以便为x,y折叠一堆类似的代码语句,z组件下至单个语句。 我还使用了你的pDomain
变量并为[0..#3] real
创建了一个类型别名,以便删除代码中的一些冗余。 哦,我删除了use
的第Math
和IO
模块,因为它们是自动用于教堂的程序。
这就是我离开的地方:
config const filename = "input.txt";
config const iterations = 100;
config const out_filename = "out.txt";
const X = 0;
const Y = 1;
const Z = 2;
const G = 6.67e-11;
config const dt = 0.1;
// Read input file, initialize bodies
var f = open(filename, iomode.r);
var reader = f.reader();
var n_bodies = reader.read(int);
const pDomain = {0..#n_bodies};
type vec3 = [0..#3] real;
var forces: [pDomain] vec3;
var velocities: [pDomain] vec3;
var positions: [pDomain] vec3;
var masses: [pDomain] real;
for i in pDomain {
positions[i] = reader.read(vec3);
velocities[i] = reader.read(vec3);
masses[i] = reader.read(real);
}
f.close();
reader.close();
for i in 0..#iterations {
// Reset forces
forces = [0.0, 0.0, 0.0];
forall q in pDomain with (+ reduce forces) {
for k in pDomain {
if k <= q {
continue;
}
var diff = positions[q] - positions[k];
var dist = sqrt(diff[X]**2 + diff[Y]**2 + diff[Z]**2);
var dist_cubed = dist**3;
var tmp = -G * masses[q] * masses[k] / dist_cubed;
var force_qk = tmp * diff;
forces[q] += force_qk;
forces[k] -= force_qk;
}
}
forall q in pDomain {
positions[q] += dt * velocities[q];
velocities[q] += dt / masses[q] * forces[q];
}
}
var outf = open(out_filename, iomode.cw);
var writer = outf.writer();
for q in pDomain {
writer.writeln("%er %er %er %er %er %er".format(positions[q][X], positions[q][Y], positions[q][Z], velocities[q][X], velocities[q][Y], velocities[q][Z]));
}
writer.close();
outf.close();
您可以考虑进行的另一个更改是使用以下整个数组语句替换更新位置和速度的forall-loop:
positions += dt * velocities;
velocities += dt / masses * forces;
其中主要的权衡是forall将使用单个并行循环以融合方式实现语句,而整个数组语句则不会(至少在编译器的当前版本1.18版本中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.