One of the big differences between C/C++ and Fortran when it comes to speed is that the former languages use pointers which can be aliased and therefore a compiler needs to load in the data at each loop iteration while Fortran's allocatable does not have that problem.
C offers the keyword restrict
so you ensure the compiler that the pointer is not being aliased. With c++
, the standard does not offer this option. I am not willing to use a vendor extension since I am concerned about portability, but also this is a critical part of my application. Hence, I don't won't to rely on things outside standard when they are fundamental to my app.
QUESTION
My question is if there is a way to ensure the c++ compiler that a specific pointer argument is not being aliased. Will C++ reference be of any help (i.e. having references as arguments pass by value is not an option since we are dealing with very large arrays)?, or should I simply write those routines in C and calling them from my C++ app?
void HEAVY_CALC( double *p1, double *p2 , double *p3, int n1)
{
for(int i = 0; i<n1 ; i ++ ) {
p1[i] = Func_1( ) ;
p2[i] = Func_2( ) ;
p3[i]= Func_3( ) ;
}
}
Since pointers here could be alised by others compiler will load p1,p2,p3 at each i
iteration. In C
if I add restrict
that will be resolved. What happens if I add a reference instead of pointer i.e.
void HEAVY_CALC( double* &p1, double *&p2 , double* &p3, int n1)
Would that change anything?
[Is] there is a way to [promise] the [C++] compiler that a specific pointer argument is not being aliased [..] without having to go beyond the standard[?]
No, there isn't.
You can usually use the non-standard __restrict
instead, which was introduced to major toolchains to plug exactly this gap. Portability isn't such a concern here as you might think, since GCC, Clang and Visual Studio all deliberately support the same keyword.
Allegedly, it's not trivial to add restrict
to the language, even though such a keyword has (as indicated above) been shown to be completely implementable. Indeed, it's been done already.