I was wondering if there is a specific way to optimize only some functions (which in most cases) should not be required to be debugged.
As an example, say I have a 3x3 matrix implementation.
class Mat3
{
Vec3 columns[3];
Vec3 rowAt(int i) const { return Vec3(columns[0][i], columns[1][i], columns[2][i]); }
Vec3 operator * (const Vec3& v)
{
return Vec3(dot(rowAt(0), v),
dot(rowAt(1), v),
dot(rowAt(2), v));
}
// versus, which is more efficient in unoptimized compiler generation
// but a lot less readable and duplicate code
Vec3 operator * (const Vec3& v)
{
return Vec3(columns[0][0].x * v.x + columns[1][0].y * v.y + columns[2][0].z * v.z),
columns[0][1].x * v.x + columns[1][1].y * v.y + columns[2][1].z * v.z),
columns[0][2].x * v.x + columns[1][2].y * v.y + columns[2][2].z * v.z));
}
};
When optimized the copies created by rowAt() will be optimized out. But when running non-optimized code this will create extra copies of Vec3
that will produce slower code. This sort of function isn't going to need to be debugged very often (usually once it is implemented and such).
Is there any way to make the compiler optimize only specific functions? There are some other use cases (in the case of templates and functors), which this would be useful.
You can compile your functions separately in different .cpp
files. For each .cpp
file you can compile them using different parameters, for example, g++ -o -O3 your_need_optimized.cpp
. Then you can link them together to produce the executables.
Or you can do as Drew McGowen pointed out that you can put
#pragma GCC optimize ("-O3")
in your cpp file before the function you want to optimize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With