Saturday, May 5, 2012

Using ccache to speed up kernel compilation

We are going to use "ccache" to speed up our Linux kernel compilation. This neat tool caches the output of C/C++ compilation so the next time the results can be taken from the cache. It can result in 5-10 times speed improvements.

Update : Recorded a short video on it !

1. First we need to install ccache which is already available in Ubuntu repositories
$sudo apt-get install ccache
2. Now let us configure our system to use ccache. Edit your ~/.bashrc
$vim ~/.bashrc
And add the following lines to the end of the file
# ccache
export CCACHE_DIR="/home/prashants/.ccache"
export CC="ccache gcc"
export CXX="ccache g++"
export PATH="/usr/lib/ccache:$PATH"
Replace the /home/prashant/.ccache folder to your own home folder. It is a empty folder that ccache will use to store the result of the compilation. You can use any other folder name of your choice.

The /usr/lib/ccache folder is automatically created by ccache and it contains symlinks to ccache for gcc/g++ compiler names. By adding it to our PATH environment variable, ccache will be called instead of gcc compiler.
$ls /usr/lib/ccache
Now to apply the changes in the ~/.bashrc file
$source ~/.bashrc
3. Next we need to setup the maximum cache size
$ccache -M 2G
This limits the cache size to 2GB. You can change it to something more if you have enough free space.

4. You are done ! Next time you run gcc/g++/make commands it will use ccache. You can monitor the current usage of ccache by executing
$watch -n1 -d ccache -s
5. Lets try it out ! Download the latest linux kernel source from and compile it. Simultaneously keep a terminal open with the above command running and you will see this

Combining ccache along with distributed kernel compilation can give really amazing results ! Read about the distributed kernel compilation in my previous article here.