Using functions slows codes

Hello,

I was working on a project and I started to use functions to make the code simpler. As the computing times started to get high, I started to optimize the code. I found that the main wastage of time was calling functions, because if the code inside the function is just written in the place where you call the function, It is much faster. I wrote a minimal example to show what i mean:

func bool example1(int[int] & I){
	for(int i=0; i<I.n; i++) I(i) = i;
	return 0;
}
real[int] timer(2);
int repetitions = 100;
int length = 1e6;
for(int j=0; j<repetitions; j++){
    int[int] I(length);
    real time = clock();
    example1(I);
    timer(0) += clock()-time;
}
for(int j=0; j<repetitions; j++){
    int[int] I(length);
    real time = clock();
    for(int i=0; i<I.n; i++) I(i) = i;
    bool exa = 0;
    timer(1) += clock()-time;
}
timer /= repetitions;
cout<<"Mean of times per iteration with function call: "<<timer(0)<<endl;
cout<<"Mean of times per iteration without function call: "<<timer(1)<<endl;

My question is, am I doing something wrong? Is there a way to use functions whithout slowing the codes? Maybe I should imput the data into the function in another form (like in C++ you do by using pointers).

Thank you for your help.

Maybe you could try using macros instead of functions (macros just copy a piece of code in the compilation process).
Furthermore I think loops in FreeFem are generally slow. You could try to use implicit for loops (see documentation) which I think are faster.

Thank you for answering this quickly,

I will try to use macros. I also wanted to store the functions on an .idp, I assume I can also store Macros there?

Loops in the examples where only to do something inside the function to show the slow it brings. Anyway, thank you for the advice.

Yes, you can also define the macros in different files. A lot of FreeFem utilities are defined in macros in FreeFem-sources/idp at develop · FreeFem/FreeFem-sources · GitHub