Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an optimization flag to a Go compiler?

Tags:

go

To compile a Go program you type go build myprogram.go, can you pass an optimization flags along or the code is always compiled in the same way? I am talking about speed optimizations, code size optimizations or other optimizations.

I know if you use gccgo you just pass -O2 or -O0 but my question is about an official Go compiler go.

like image 869
exebook Avatar asked Jul 10 '17 03:07

exebook


People also ask

What does optimization flag do?

Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program. The compiler performs optimization based on the knowledge it has of the program.

What is optimization level for GCC compiler?

GCC has a range of optimization levels, plus individual options to enable or disable particular optimizations. The overall compiler optimization level is controlled by the command line option -On, where n is the required optimization level, as follows: -O0 . (default).

Which property is the most important for an optimizing compiler?

Defining Compiler Optimizations. An optimization is the process of transforming a piece of code into another functionally equivalent piece of code for the purpose of improving one or more of its characteristics. The two most important characteristics are the speed and size of the code.


2 Answers

Actually no explicit flags, this Go wiki page lists optimizations done by the Go compiler and there was a discussion around this topic in golang-nuts groups.

You can turn off optimization and inlining in Go gc compilers for debugging.

-gcflags '-N -l'
  • -N : Disable optimizations
  • -l : Disable inlining
like image 109
jeevatkm Avatar answered Sep 21 '22 22:09

jeevatkm


If you're looking to optimize the binary size, you can omit the symbol table, debug information and the DWARF symbol table by passing -s and -w to the Go linker:

$ go build -o mybinary -ldflags="-s -w" src.go

(source blog post which includes some benchmarks)

like image 45
fstanis Avatar answered Sep 19 '22 22:09

fstanis