From the distance of over 30 years of programming experience, I would allow myself to share the following.
Algorithms for estimating source code metrics are relatively subjective.
You know that a qualitative program can work well by ensuring that it does not cease to work due to any error. Anticipating and processing all possible types of errors requires extra time and programming code. In this sense, the program will not be optimal in terms of speed, its basic tasks.
Another program can work very fast, but it will not have the strength of the above program.
If the question is - optimization with regard to the number of sub-programs that can be combined, or cycles that can be optimized, or logical expressions that can be simplified, it depends on the language you are using. If this language has a compiler, then the compiler does it partially for you.
Otherwise, the algorithms for estimating source code depend on the specific programming language.
The best algorithm for creating quality code is a precisely designed pre-release plan of what and how the program should do. Then, make a detailed block algorithm and at the end select the appropriate programming language and write the code.