I am a competitive programmer and I use pragmas for my codes. The pragmas that I use are:
#pragma GCC optimize("O3")
#pragma GCC optimization("Ofast,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
But recently I submitted a code where the code with pragmas used more time than the code without pragmas? Can anyone please help me understand when to use such pragmas and when to not use them?
I tried to search it online on Google and Codeforces but there is no good source or article to study pragmas from in detail. Could anyone please help?
These
#pragmas control the optimizations applied by the compiler. Outside of competitive programming, it is much more common to configure this through the command line options than by the use of#pragma, so you will be much more likely to find good resources when searching for the command line options. For example, look at the official documentation for gcc's optimization options.As to whether a particular option will make your code faster: You won't know until you try. The optimization was built in the first place because it will be faster for some use cases, but whether your specific program will benefit from it? That is a very difficult question to answer. Even compiler writers with years of experience get surprised by this sometimes. The best thing you can do is understand how a particular optimization actually influences the generated machine code. After a while, you may be able to build a crude intuition for what the performance benefits are.
But in order to be sure, you really have to measure. This is an enormously complex problem with many factors influencing the final outcome.