使用ccache加快编译速度

ccache是一个编译器缓存,可以将编译的结果缓存起来。这样尽管第一次编译会花费长一点的时间,不过之后再次编译将变得非常非常快。


1、安装


主流的linux发行版应该都有这个包,对于Debian系列的可以执行以下命令安装:


sudo apt-get install ccache

2、使用


安装之后基本不用进行什么配置就可以直接使用了。

例如之前要编译一个hello.c文件要执行命令:


gcc hello.c -o hello

现在是:


ccache gcc hello.c -o hello

ccache默认是将结果缓存保存到 $HOME/.ccache 目录下。如果想要修改这个目录,可以修改 CCACHE_DIR 环境变量。例如:


export CCACHE_DIR=/ramdisk/ccache

如果觉得每次都在命令前加上ccache比较麻烦的话,有一个一劳永逸的办法。执行如下命令:


cp ccache /usr/local/bin/
ln -s ccache /usr/local/bin/gcc
ln -s ccache /usr/local/bin/g++
ln -s ccache /usr/local/bin/cc
ln -s ccache /usr/local/bin/c++

不过这样的话每次都是使用的ccache,不太灵活。这个就要自己取舍了。


3、实例


接下来通过一个例子来看看使用ccache和不使用的差别。

作为一个Python程序员,我们就来编译一个Python试试。


$ tar xf Python-2.7.3.tar.gz
$ cd Python-2.7.3
$ ./configure
$ time make
make 96.49s user 5.10s system 93% cpu 1:48.77 total

首次编译花了1分48秒。


$ time make
make 0.12s user 0.03s system 88% cpu 0.172 total
$ make clean
$ time make
make 96.46s user 4.98s system 95% cpu 1:46.43 total

清除结果之后再次编译,还是花了1分46秒。


再来看看使用ccache后的结果:


$ tar xf Python-2.7.3.tar.gz
$ cd Python-2.7.3
$ ./configure
$ time make
make 99.42s user 5.84s system 93% cpu 1:52.95 total

$ time make
make 0.16s user 0.00s system 89% cpu 0.178 total
$ make clean
$ time make
make 3.36s user 1.41s system 52% cpu 9.093 total

首次编译花了1分52秒,之后都是只花了几秒。


查看ccache的统计信息:


$ ccache -s
cache directory /home/longchang/.ccache
cache hit (direct) 250
cache hit (preprocessed) 4
cache miss 349
called for link 132
alled for preprocessing 84
compile failed 29
preprocessor error 28
bad compiler arguments 5
unsupported source language 6
autoconf compile/link 224
no input file 24
files in cache 710
cache size 30.3 Mbytes
max cache size 1.0 Gbytes

清除掉缓存后再次编译:


$ ccache -c
Cleaned cache

$ make clean
$ time make
make 99.36s user 5.94s system 92% cpu 1:53.47 total

$ make clean
$ time make
make 3.48s user 1.42s system 54% cpu 9.049 total

ccache手册: http://ccache.samba.org/manual.html