Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure the quality of my code?

I have some experience with coding but one of the biggest questions which annoying me is how to improve my code.

I every time check the complexity, readability and the correctness of the code but my question is how I can measure the size and the time of specific commands.

For example:

when I have the next problem:

A is an integer

B is an integer

C is an integer

if - A is bigger the B assign C=A

else - C=B

for that problem, we have 2 simple solutions -

1. use if-else statement

2. use ternary operator

for a dry check of the size of the file before compilation, i get that the second solution file is less from the first in a half (for 1000000 operations I get a difference of some MB).

My question is how I can measure the time difference between some codes which make the same operation but with different commands, and how much the compiler makes optimization for commands which is close like the 2 from the example.

like image 210
Bizzu Avatar asked Sep 24 '17 13:09

Bizzu


1 Answers

The best and most direct way is to check an assembly code generated by your compiler at different optimization level.

//EDIT

I didn't mention benchmarking, because your question is about checking the difference between two source codes using different language constructions to do the same job.

Don't get me wrong, benchmaking is recommended solution of assuring general software performance, but in this particular scenario, it might be unreliable, because of extremely small execution time frames basic operations have. Even when you calculate amortized time from multiple runs, the difference might be to much dependend on the OS and environment and thus pollute your results.

To learn more on the subject I recommend this talk from Cppcon, it's actaully kinda interesting.

But most importantly,

Quick peek under the hood by exploring assembly code can give you information whether two statements has been optimized into exactly same code. It might not be so clear from benchmarking the code.

In the case you asked (if vs tenary operator) it should always lead to same machine code, because tenary operator is just a syntactic sugar for if and physically it's actually the same operation.

like image 154
Outshined Avatar answered Sep 17 '22 22:09

Outshined