On 21/12/2023 20:57, Jonathan Wakely via Gcc-help wrote:
On Thu, 21 Dec 2023, 19:33 Aran Nokan via Gcc-help, <gcc-help@xxxxxxxxxxx>
wrote:
Hello GCC Community,
I recently conducted an experiment where I tested the impact of different
GCC optimization levels on the performance of a code
<https://github.com/leechwort/levenberg-maquardt-example>. I observed that
higher optimization levels didn't necessarily result in faster code
execution.
Is it correct or I have made a mistake? Do we have any other parameters for
optimization?
There is no guarantee that optimization make code faster, except that -O0
will invariably be slower.
However, I suspect the problem is that your makefile only builds the .o
objects once, for the first target that needs them. That means they will be
optimized (or not optimized) according to the CFLAGS set when building that
first target.
Unless you do 'make clean' before building each target, you weren't
actually testing what you intend to test.
For this test, since there are not many source files, I'd put them all
on the same gcc line :
default: all
.PHONY: all
OPTS = 0 1 2 3 g fast
PROGS = $(foreach opt, $(OPTS), test.$(opt))
all: $(PROGS)
CC = gcc
CFLAGS_COMMON = -I.
LDLAGS = -lm
DEPS = levmarq.h makefile
SRC = main.c levmarg.c
test.% : $(SRC) $(DEPS)
gcc -o $@ $(CFLAGS) $(LDLAGS) -O$* $(SRC)
clean:
rm -f $(PROGS)
(I haven't tried the makefile at all, but it might be a starting point
for the OP.)
My make file was as follows:
CC=gcc
CFLAGS_COMMON=-I.
LDLAGS=-lm
DEPS = levmarq.h
OBJ = main.o levmarq.o
%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS) $(LDLAGS)
main: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LDLAGS)
# No optimization
main_no_opt: CFLAGS += -O0
main_no_opt: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LDLAGS)
# Basic optimization
main_opt1: CFLAGS += -O1
main_opt1: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LDLAGS)
# Moderate optimization
main_opt2: CFLAGS += -O2
main_opt2: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LDLAGS)
# High optimization
main_opt3: CFLAGS += -O3
main_opt3: $(OBJ)
gcc -o $@ $^ $(CFLAGS) $(LDLAGS)
# Clean rule
clean:
rm -f *.o main main_no_opt main_opt2 main_opt3
Best regards,
Aran