jajajen
jajajen

Reputation: 29

pragma gcc optimize in function

In C code, I want to optimize few 'for' loops in function, but not in whole function. What I want to do is,

int main(){
for(int a=~~~~~)
for(int b=~~~~~)

I want to optimize first for loop using O3 to compare with second for loop. However,

#pragma GCC push_options

is not allowed to use in function. Is there any way that I can use optimization in function? Thanks!

Upvotes: 0

Views: 928

Answers (1)

Kitsu
Kitsu

Reputation: 3435

Fairly useful way is to split up a code to functions, e.g.:

int main() {
  for (int i = 0; i < 5; ++i) printf("%d", i);

  for (int j = 0; j < 5; ++j) printf("%d", 5 - i);
}

then becomes


int main() {
  fn1();
  fn2();
}

inline void fn1() {
  for (int i = 0; i < 5; ++i) printf("%d", i);
}

// here you can place pragma

inline void fn2() {
  for (int j = 0; j < 5; ++j) printf("%d", 5 - i);
}

Most probably, functions would be inlined and compiler can understand its pragams as according to doc:

#pragma GCC optimize (string, …)

This pragma allows you to set global optimization options for functions defined later in the source file.

Moreover, I would consider to put these functions to files, so you are able to have a finer-grained flags specific to a compilation unit and do not depend on compiler-specific pragmas (which I believe does not work on clang/inter-compiler/msvc/etc).

Upvotes: 2

Related Questions