3 ms·
The author's point is well taken, but his example leaves a lot to be desired: If you look at that loop, it can be parallelized or vectorized without any proble
by yummyfajitas 15y ago
The author's point is well taken, but his example leaves a lot to be desired:
If you look at that loop, it can be parallelized or vectorized without any problem if and only if the array pointed to by x and the array pointed to by y are completely distinct with no overlap. But there's no way to write code in C or C++ that guarantees that.
double* doMath(double** y) {
double** x = allocateNew2DArray(20000, 20000);
for (int i=0; i < 20000) {
for (int j=0; j < 20000) {
x[i][j] = y[i-2][j+1] * y[i+1][j-2];
}
}
return x;
}
All you need to do for this example is replace the fortran coding style doMath(double* x , double* y) with the c coding style doMath(double* y).
I don't think any C compilers actually do parallelize code like this, or at least they don't do much beyond using SIMD. But in principle they could.
- nitrogen 15y agoI think something may have been lost when you typed your code. y is a pointer to double, so can't accept two array subscripts (if it were "double * * y" it could, or you could keep it as a one-dimensional array and use something like y[(i - 2) * 20000 + j + 1]), and i and j don't appear to be incremented anywhere.
- yummyfajitas 15y agoThanks, fixed the "double * * y". The i and j not being incremented is actually an error in the original blog post - I'll leave it here for consistency.
- nitrogen 15y agoThe i and j not being incremented is actually an error in the original blog post - I'll leave it here for consistency. Ah. In that case, I wonder how the author managed to get an infinite loop to complete in 0.8 seconds ;).
- mturmon 15y agoThe use in the blog post of this example, with 2d arrays in C implemented through pointers-to-pointers, perplexed me. If you care about efficiency, you don't use pointers-to-pointers for rectangular matrices. You use 1D vectors and strides. For instance, this is how numerical linear algebra codes typically represent matrices. This approach also generalizes well to N-dimensional problems. The pointers-to-pointers idiom is picked up by some people due to its use in Numerical Recipes. Of course, NR used it to make C look like Fortran, because they were comfortable with Fortran. Another NR artifact is the gyrations used to make C arrays appear to start at 1 rather than 0. Which is a hoot. I agree with some comments above that the Fortran 90 matrix constructs are an improvement on C's capabilities.