
未緩存前:
time ./x bin.tar
file size is 816322560
816322560 bytes read now
real 0m3.378s
user 0m0.000s
sys 0m0.996s
被緩存後:
real 0m0.770s
sys 0m0.768s
硬碟讀取性能:
hdparm -t /dev/sdb
/dev/sdb:
Timing buffered disk reads: 2454 MB in 3.00 seconds = 817.84 MB/sec
10塊實體磁盤,做了Raid10,是以讀性能高,達每秒817.84MB。
測試程式:
// 非優化方式編譯:g++ -g -o x x.cpp
#include
// 帶一個參數,為被讀取檔案的大小
int main(int argc, char* argv[])
{
int fd = open(argv[1], O_RDONLY);
if (-1 == fd)
{
perror(strerror(errno));
exit(1);
}
struct stat st;
if (0 == fstat(fd, &st))
// 輸出檔案大小,機關為位元組
printf("file size is %d\n", st.st_size);
// 一次性将整個檔案讀到記憶體中
char* bytes = new char[st.st_size];
int bytes_read = read(fd, bytes, st.st_size);
// 顯示實際成功讀取的位元組數
printf("%d bytes read now\n", bytes_read);
delete []bytes;
close(fd);
return 0;
}
清緩存:
使用free指令觀察下列操作的變化,以root使用者執行:先執行下sync指令,以将資料更新到磁盤,再執行echo 3 > /proc/sys/vm/drop_caches,以清除系統的cached。
檔案記憶體的緩存會反應出free指令輸出的cached值的變化,實際就是Page cache,檔案内容的讀取會緩存在這裡。如果讀取一個大檔案,可以看到cached的值明顯增漲,并且增漲大小差不多就是檔案的大小,buffers相當于cached的元資訊,比如檔案的inode。
cached影響檔案的讀取性能,而buffers影響到檔案的打開性能。
drop_caches使用彙總:
echo 0 > /proc/sys/vm/drop_caches
不做釋放
echo 1 > /proc/sys/vm/drop_caches
釋放Page Cache
echo 2 > /proc/sys/vm/drop_caches
釋放Dentries/inodes Cache(其中,Dentry是目錄資訊,inode是檔案資訊)
echo 3 > /proc/sys/vm/drop_caches
釋放Page和Dentries/inodes Cache
這個特性由2.6.16核心開始提供,參考資料:
1) /proc/sys/vm/drop_caches
<a href="http://linux-mm.org/Drop_Caches">http://linux-mm.org/Drop_Caches</a>
2) Linux Buffer vs Cache explained
<a href="http://random-techbits.blogspot.com/2012/06/linux-buffer-vs-cache-explained.html">http://random-techbits.blogspot.com/2012/06/linux-buffer-vs-cache-explained.html</a>