我们需要一个应用程序来尽可能地保证当它报告一条记录时,它确实是持久的。我知道要做到这一点,你使用fsync(fd)
. 然而,出于某种奇怪的原因,使用 fsync() 似乎加快了写入磁盘的代码,而不是像预期的那样减慢它。
一些示例测试代码返回以下结果:
no sync() seconds:0.013388 writes per second:0.000001
sync() seconds:0.006268 writes per second:0.000002
下面是产生这些结果的代码:
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
void withSync() {
int f = open( "/tmp/t8" , O_RDWR | O_CREAT );
lseek (f, 0, SEEK_SET );
int records = 10*1000;
clock_t ustart = clock();
for(int i = 0; i < records; i++) {
write(f, "012345678901234567890123456789" , 30);
fsync(f);
}
clock_t uend = clock();
close (f);
printf(" sync() seconds:%lf writes per second:%lf\n", ((double)(uend-ustart))/(CLOCKS_PER_SEC), ((double)records)/((double)(uend-ustart))/(CLOCKS_PER_SEC));
}
void withoutSync() {
int f = open( "/tmp/t10" , O_RDWR | O_CREAT );
lseek (f, 0, SEEK_SET );
int records = 10*1000;
clock_t ustart = clock();
for(int i = 0; i < records; i++) {
write(f, "012345678901234567890123456789" , 30 );
}
clock_t uend = clock();
close (f);
printf("no sync() seconds:%lf writes per second:%lf \n", ((double)(uend-ustart))/(CLOCKS_PER_SEC), ((double)records)/((double)(uend-ustart))/(CLOCKS_PER_SEC));
}
int main(int argc, const char * argv[])
{
withoutSync();
withSync();
return 0;
}