1MBi文件,一次性写入1MBi 。注:以前全部按照IEC标准
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
int main(int argc,char *aa[]){
-
int fd,fd1;
-
char buffer[1048576];
-
fd=open(aa[1],O_RDONLY,S_IRUSR);
-
if(fd==-1){
-
printf("file not found.\n");
-
return -1;
-
}
-
fd1=open(aa[2],O_CREAT | O_WRONLY,S_IRUSR);
-
if(fd1!=-1){
-
}
-
ssize_t n;
-
while(n=read(fd,buffer,1048576)){
-
write(fd1,buffer,n);
-
printf("Writing.....\n");
-
}
-
close(fd);
-
close(fd1);
- }
点击(此处)折叠或打开
-
#include <stdio.h>
-
#include <sys/types.h>
-
#include <sys/stat.h>
-
#include <fcntl.h>
-
#include <unistd.h>
-
int main(int argc,char *aa[]){
-
int fd,fd1;
-
char buffer[1024];
-
fd=open(aa[1],O_RDONLY,S_IRUSR);
-
if(fd==-1){
-
printf("file not found.\n");
-
return -1;
-
}
-
fd1=open(aa[2],O_CREAT | O_WRONLY,S_IRUSR);
-
if(fd1!=-1){
-
}
-
ssize_t n;
-
while(n=read(fd,buffer,1024)){
-
write(fd1,buffer,n);
-
printf("Writing.....\n");
-
}
-
close(fd);
-
close(fd1);
- }

为了测试准确,第一次写入数据后,为了保证测试的准确性,需要清除了cache和buffer。echo 3 > /proc/sys/vm/drop_caches
可以看出来一次性写入1M完成写入时间更快,为什么会有这样的结果呢?strace看一下
1次性写入1MBi

1KBi写入1024次

结论:user近乎不用时间,sys占用了大部分时间,其余时间都用在kernel层和user层的切换,sys用的时间为systemcall上,可以简单了解下Linuxkernel的架构,主要分为内核层和用户层(kernelspace和userspace),用户层的应用程序会通过调用systemcall转入内核层对数据进行最终的读写操作。

总之尽量减少系统调用的频繁使用可以减少程序的执行时间,当然不断的读写也会增加磁盘I/O的负载,所以对系统的优化要从优化程序上做起。