Required compile flags in order to user perf

I am trying to understand linux perf and hotspot to understand call stacks/trace of my c++ application.

Should the program compiled in debug mode or in release mode ? Assuming I have only one file inline.cpp. I have seen in one of the example using

g++ -O2 -g inline.cpp -o inline
perf record --call-graph dwarf ./inline

I am wondering is it necessary to compile the program in debug (-g) and optimization -O2 ? What are flag that the executable is compiled in order make it useful to run with perf record ?

Does it make any difference if we compile the program with out compiler flags ?

g++ inline.cpp -o inline


First of all, -g and -O2 aren’t opposites. -g specifies that debugging symbols will be generated, so that you can associate hotspots with actual lines of code. -O2 specifies that code optimization should be performed; this is ordinarily not done with code you intend to run in a debugger because it makes it more difficult to follow the execution.

A profiler measures the performance of an executable, not of source code. If you profile an unoptimized executable you’ll see where the unoptimized executable’s performance problems are, but those may be different problems than in the optimized executable. Presuming you care about the performance of the optimized executable (because it’s what users will ordinarily be running) you should be profiling that. The use of -O2 will definitely make it harder to understand where the performance problems are, but that’s just the nature of profiling code.