#include
#include
#include
#include
int main()
{
char buffer[1024];
int in,out;
int nread;
//打开文件以只读形式
in = open("./a.txt",O_RDONLY);
//打开文件通过写的方式
out = open("./b.txt",O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR);
//从一个文件读入1024字节写入另外的文件
while( ( nread = read(in,buffer,sizeof(buffer)) ) > 0)
{
write(out,buffer,nread);
}
exit(0);
}
使用如下命令利用time工具可以测试程序的效率和资源的使用情况
TIMEFORMATE="" time ./readfile
[leconte@localhost test]$ time ./test
real 0m0.020s
user 0m0.000s
sys 0m0.018s
结果表明,程序实际运行时间0.020s,用户态运行时间接近0s,内核态运行时间0.018s.这是因为我们主要操作是使用文件相关的系统调用,程序大部分时间工作在内核态。
需要注意的是,real并不等于user+sys的总和。real代表的是程序从开始到结束的全部时间,即使程序不占CPU也统计时间。而user+sys是程序占用CPU的总时间,这个时间跟系统负荷无关,因此real总是大于或者等于user+sys的。
例如我在上述程序中加上sleep(1):
for(i=0;i