Making the code faster is kind of an important thing in the coders life for sure. Every programmer has a few stories about speeding up the project a thousandfold and saving it in the last minute. Truth is sometimes the code runs so slow, it is just not feasible to actually use it. Who wants a phone app that starts in 20 minutes or a database management software that runs a query for three days, right?
But here is the thing: how do you do it? How do you make the code a lot faster? Not just 3% or 10%, but maybe hundreds and hundreds time faster? Well, there is a magic tool called profiling...
No, not that profiling, not the one that they do in the movies and in the TV, this is a lot more interesting. Well, it is a lot more interesting for me, and I am selfish like that... oh, don't profile me, profile this!
So here is an easy way to do it. Install the tool called vallgrind on your Linux and install the GUI application called kcachegrind. These are all you need, it is simple, I tell you.
You need to run your program. You need to give it enough thing to do so it breaks a sweat, but not too much, because when you make your measurements the code will run a lot slower than normally. You may already have some unit tests or something that do some heavy lifting. Maybe a functional test... So you run your code with valgrind like this:
valgrind --tool=callgrind yourprogram yourprogramsoptions
You wait until the program finishes, or you can even press Ctrl+C if it ran for long enough. When you finished running it you will see one or more files are created in the current directory with the name that looks like callgrind.out.SOMETHING. Then you can view them starting the kcachegrind UI program, like this:
And that's it. A call graph will be presented for you and you will see the percents representing how much time a certain part of your code spent there. I find it is useful to go to the View menu and turn off the Cycle Detection, but you may find that is not what you need. Anyhow, the tool will be great, if you don't know it, you will be amazed and it will server you well. Maybe it will even save your job, who knows?
Because here is the thing, knowing is half of the battle and without knowing you are lost. You will not know where your program spends most of the time, you will not know where can you actually make a difference. Optimizing a code, making it ten times faster where it spends 1% of the time speeds up the program how much? That's right, it will be 0.9% faster. And speeding up tenfold where it spends 99% will be, well, you do the math.
Not to mention all those things that you did not know happening. Like when you realize your log file handling actually blocks all your threads and slows down the code so that it is practically at a standstill. When you remove one messed up part of the code and you realize your code was actually very fast from the beginning... except the one little piece that now you have to rewrite from scratch.