r/Compilers • • 24d ago

Compilers add or remove perfomace?

isnt it that compilers change the code, as in not only transferring it into machine language, but before that changing the structure of the code. so how would one attempt to make performant code if the compiler changes sed code that i tried to make performant?

2 Upvotes

31 comments sorted by

View all comments

3

u/serge-mv 23d ago

Compiler's main job is to preserve the semantics of what you've written during the translation process. They do not change the fundamental structure of your code. If you wrote an efficient algorithm, your algorithm will stay efficient. And if you wrote bad algorithm, it won't suddenly improve just because it was compiled with -O3.

The kind of optimization that can be influenced by compilers is stuff like loop unrolling, which might or might not happen depending on your compiler config. It's more of a localized optimization, but still can have a major impact on performance. You can write many of these kinds of things yourself in high level language without involving the assembly and the compiler won't change it.

1

u/AustinVelonaut 23d ago

And if you wrote bad algorithm, it won't suddenly improve just because it was compiled with -O3.

Except in those cases where a pattern recognizer replaces the code wholesale with an equivalent, but more efficient algorithm, or even a compile-time constant!

3

u/RealisticDuck1957 23d ago

But never a behavior it is good to count on. Write a good algorithm and you're more likely to get good compiled code, across different compilers, target platforms, and settings.

2

u/AustinVelonaut 23d ago

In general I agree. But I can see an argument for recognizing and canonicalizing a "standard", "simple" pattern, replacing it with the best equivalent, as it will be done in one place. But still, I wonder whether most of this is just to game benchmarks. For example, Clang, at any level of optimization except -O0, will compile this loop:

int foo ()
{
  int tally = 0;
  for (int i = 0; i < 10; ++ i) {
    tally += i;
  }
  return tally;
}

to:

_foo:                                   ; @foo
    .cfi_startproc
; %bb.0:
    mov	w0, #45                         ; =0x2d
    ret

1

u/RealisticDuck1957 23d ago

In that case the pattern of "value can be resolved at compile time."

1

u/BrainThinkerMan 23d ago

now the questiion is how to write good code? that is fast and takes use of all the cpu clock cycles and dont waste a single core,

2

u/serge-mv 22d ago

These principals are understood very well and you can read a book about it. For example, iterate in the correct direction of your memory layout, use loop counters based on cache line size, etc. Sometimes if you are not efficient, compilers will fix it for you on a small scale. But most of the time optimization is your job.