我對大文件ftruncate
和fsync
的操作感到驚訝。我編寫了一個程序,在Linux 64位系統上創建一個空文件,將其截斷爲0xffffffff字節,之後爲fsync
。Fsync太快?
經過所有操作後,文件被正確創建爲該長度。
我看到ftruncate
的成本大約是1442微秒,而fsync
的成本只有4微秒。
這是正常的高性能?是否真的糾纏在光盤上的所有字節?如果不是,我如何確保這個同步?
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
static const size_t __tamFile__ = 0xffffffff;
int main(int, char **)
{
std::string fichero("./testTruncate.dat");
unlink(fichero.c_str());
int fd = open(fichero.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd != -1)
{
struct timeval t1, t2;
timerclear(&t1);
timerclear(&t2);
gettimeofday(&t1, NULL);
ftruncate(fd, __tamFile__);
gettimeofday(&t2, NULL);
unsigned long long msecTruncate = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;
gettimeofday(&t1, NULL);
fdatasync(fd);
gettimeofday(&t2, NULL);
unsigned long long msecFsync = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;
std::cout << "Total microsec truncate: " << msecTruncate << std::endl;
std::cout << "Total microsec fsync: " << msecFsync << std::endl;
close(fd);
}
return 0;
}
也許還應該提到,這個功能通常被稱爲稀疏文件(http://en.wikipedia.org/wiki/Sparse_file)。 – LiKao
如果你想爲所有這些零字節實際保留空間,你需要在文件上調用'posix_fallocate'。 –