On Sunday, 16 August 2015 at 13:59:33 UTC, Idan Arye wrote:
Initially I thought the Python version is so slow because it
uses `range` instead of `xrange`, but I tried them both and
they both take about the same, so I guess the Python JIT(or
even interpreter!) can optimize these allocations away.
BTW - if you want to iterate over a range of numbers in D, you
can use a foreach loop:
foreach (i; 0 .. l) {
foreach (j; 0 .. l) {
foreach (m; 0 .. l) {
a = a + i * i * 0.7 + j * j * 0.8 + m * m * 0.9;
}
}
}
Or, to make it look more like the Python version, you can
iterate over a range-returning function:
import std.range : iota;
foreach (i; iota(l)) {
foreach (j; iota(l)) {
foreach (m; iota(l)) {
a = a + i * i * 0.7 + j * j * 0.8 + m * m * 0.9;
}
}
}
There are also functions for building ranges from other ranges:
import std.algorithm : cartesianProduct;
import std.range : iota;
foreach (i, j, m; cartesianProduct(iota(l), iota(l),
iota(l))) {
a = a + i * i * 0.7 + j * j * 0.8 + m * m * 0.9;
}
Keep in mind though that using these functions, while making
the code more readable(to those with some experience in D, at
least), is bad for performance - for my first version I got
about 5 seconds when building with DMD in debug mode, while for
the last version I get 13 seconds when building with LDC in
release mode.
There is a new implementation of cartesianProduct that makes the
performance difference disappear for me with ldc and dmd. It's
not in ldc's phobos yet so I had to copy it manually, but
hopefully it will be in the next release.