转自:https://blog.csdn.net/lancegentry/article/details/8937514性能
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处连接和本声明。
本文连接:https://blog.csdn.net/lancegentry/article/details/8937514
ps:写了很长时间,因此转载请著名做者(程序圆圆圆) !!!还有这句话!!!测试
再ps一个:转载注明本空间地址呀!!!http://blog.csdn.net/lancegentry/article/details/8937514优化
一个程序使用系统调用的次数会很大程度上影响系统的性能,由于在执行系统时,会从用户代码切换执行内核代码,而后返回用户代码。优化手段就是尽可能减小系统调用。一下实验用来验证系统会付出巨大d呃开支,所用时间与电脑配置、所用的系统的内核有关,故在不一样的电脑或同一电脑的不一样系统上会有一些差别,可是结果必定是相同的。
本人使用的系统是Mac OS X 10.8.3 。.net
1.首先咱们创建一个约1Mb的文件(file.in)用于测试。创建代码以下,固然方法有不少这只是其中的一种。unix
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
file = fopen("file.in", "w");
int i = 0xfffff;
while (i--) {
fprintf(file,"%c",i%26 + 'a');
if (i%26 == 0)
fprintf(file,"\n");
}
exit(0);
}blog
2.而后编译copy_system.c get
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
char c;
int in, out;
in = open("file.in", O_RDONLY);
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while (read(in,&c,1) == 1)
write(out,&c,1);
exit(0);
}
上述代码中要注意的是#include <unistd> (unix standard)要放在第一行,由于它定义的POSIX规范的有关标志可能会影响其余的头文件。
咱们能够看一下运行的结果it
这里咱们首先看到有一个1.0M的文件file.in。而后喔们编译了copy_system.c,以后使用time命令查看执行时间。io
3.编译copy_system2.c 编译
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define BLOCK 1024
int main()
{
char block[BLOCK];
int in, out;
int nread;
in = open("file.in", O_RDONLY);
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while ((nread = read(in,block,sizeof(block))) > 0)
write(out,block,nread);
exit(0);
}
这里咱们经过复制数据块的方式来减小系统调用(每次复制1K),看看结果(顺道验证刚才文件确实生成了。。。)
我把上一次的执行也截取了下来以便比较,如今咱们能够看到时间差距仍是很是明显了,咱们这是减小约2000次(2048)的系统调用所节省的时间。而且咱们看到这两个程序执行时间的差距仍是巨大的。那么是否是越大越好呢?
为了实验放便咱们将 copy_system2.c中的#define BLOCK 1024删除即为下面代码
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
char block[BLOCK];
int in, out;
int nread;
in = open("file.in", O_RDONLY);
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
while ((nread = read(in,block,sizeof(block))) > 0)
write(out,block,nread);
exit(0);
}
这样咱们就能够很方便的进行实验了。实验结果以下
这里咱们使用 -Dname=value 的命令选项在编译时定义BLOCK变量。由于我使用的是64位系统因此在后期这个时间依旧在有减少的趋势,不过能够看出在256后这个值已经变化很小了。在1024后这些值开始了摆动,而且失去了以前的规律(system time每次减少一倍,2048和4096的数据(倒数第3个和倒数第1个))。这是由于硬件会限制对底层系统调用一次能读写的数据块大小。
最后但愿你们能从本文中有所收获。2013.05.16 23:00End ————————————————版权声明:本文为CSDN博主「程序圆圆圆」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处连接及本声明。原文连接:https://blog.csdn.net/lancegentry/article/details/8937514