-3

Let's say there's this code:

int foo() {
//code
}

int bar() {
//code
}

And if it's known for a fact that foo is called many times and bar is not called very much, how can the compiler be informed of this so that it optimises foo for speed and bar for size?

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Shambhav
  • 813
  • 7
  • 20

1 Answers1

1

The function attributes hot and cold can be used for this. Use the attribute hot for functions which will be executed more(in this case, foo) and cold for functions which won't be executed often(in this case, bar).

Like this:

__attribute__ ((hot)) int foo() {
//Will be optimised for speed.
}

__attribute__ ((cold)) int bar() {
//Will be optimised for size.
}

More about this and other extensions in https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes. These attributes can be used in labels as well.

A better option is to use profile guided optimisation: How to use profile guided optimizations in g++?. It will take more time as the program needs to be compiled twice and tested once. So, the above method using hot and cold attributes is better for developing and profile guided optimisation is better for releases. If profile guided optimisation is used, then the attributes hot and cold will be ignored.

Shambhav
  • 813
  • 7
  • 20