Take Care of Expensive Calls
It is clear that when we are interested in optimizing the code, we always want to get rid of the expensive operations (that take more time) with inexpensive calls. System calls in general are expensive operations. Let us have a look at some of the expensive system calls:
fork: A fork system call is very useful. It isn't slow, but if we use it frequently, it can add up. Consider a scenario where a web server might fork for each new request. This is not a good practice, and
select()can be used for multiplexing.
exec: This is one used immediately after a fork. This call can be very expensive as the new program will have to a lot of initialization such as loading libraries, etc.
system: This invokes a shell to run the specified command and invoking a shell can be quite expensive. Therefore, frequently using a
systemis definitely a bad idea.
If we come across a code piece such as
system("ls /etc"); we can see how expensive this is. The program first has to fork and execute the shell. The shell needs to do initialization and then it forks and executes
ls. Definitely not a piece of code to desire.
The first step in getting the system tweaked for both speed and reliability is to chase down the latest versions of required device drivers. Another useful key is to understand what the bottlenecks are and how they can be taken care of. We can come to know about the various bottlenecks by running various system monitoring utilities, such as the
Optimizing Disk Access
It's always worth giving attention to disk access. There are various techniques that can produce significant improvements in disk performance.
First, read up on the
hdparm command and you will notice that it sets various flags and modes on the IDE disk driver subsystem. There are two options we need to look at – the
-c option can set 32 bit I/O support and the
-d option enables or disables the
using_dma flag for the drive. In most cases, this flag is set to 1, but if yours hasn't, then you are going to suffer from performance issues. Try changing it by placing a command like this
hdparm –d 1 /dev/hda
at the end of the /etc/rc.d/rc.local file.
hdparm –c 1 /dev/hda
at the end of /etc/rc.d/rc.local file will set the support for 32 bit I/O.
GNU profiler (gprof)
After we have taken enough measures in optimizing our code, the compiler can be helpful with optimization as well. One tool that we can use to analyze our program's execution is the GNU profiler (gprof). With this, we can come to know where the program is spending most of its time. With profile information we can determine which pieces of program are slower than expected. These sections are definitely good candidates for to be rewritten so that program can execute faster. The profiler collects data during the execution of a program. Profiling can be considered as another way to learn the source code.