zoukankan      html  css  js  c++  java
  • UC编程:通过fwrite()和write()比较标准库函数和系统调用的速度

    fwrte是C标准库中提供的函数,是对write函数的扩展与封装,write则是Unix系统提供的函数。按照常理来讲,系统调用肯定比使用库快的多,但是事实正好相反 Why?原因就在于缓冲的问题,fwite会在内存中开辟缓冲区,来避免频繁的I/O,所以速度比系统调用要快(更多比较“open/read/write和fopen/fread/fwrite的区别”) 为了直观的比较一下fwrite和write的速度。我们来做一个简单的测试: fwrite.c [c] #include <stdio.h> int main(void) { FILE *stream; int i; char str[] = "qwertyuiop "; if ((stream = fopen("fwrite.txt", "w")) == NULL) { fprintf(stderr, "Cannot open output file. "); return 1; } for(i=0; i<100000; i++) { fwrite(str, sizeof(str), 1, stream); } fclose(stream); /*关闭文件*/ return 0; } [/c] 运行时间: [code] real 0m0.009s user 0m0.003s sys 0m0.005s [/code] write.c [c] #include <stdio.h> #include <fcntl.h> int main(void) { int fd; int i; char str[] = "qwertyuiop "; if ((fd = open("write.txt", O_RDWR|O_CREAT|O_TRUNC, 00664)) < 0) { fprintf(stderr, "Cannot open output file. "); return 1; } for(i=0; i<100000; i++) { write(fd, str, sizeof(str)); } close(fd); /*关闭文件*/ return 0; } [/c] 运行时间: [code] real 0m0.189s user 0m0.008s sys 0m0.181s [/code] 果然,从程序运行时间上看,使用标准库函数速度比直接系统调用快了很多 从程序的可移植性角度来讲,使用标准库函数也是一个好的习惯 而系统调用则是用在和系统关联度很高的地方
  • 相关阅读:
    Autofac(01)
    深入理解ADO.NET Entity Framework(02)
    使用excel 数据透视表画图
    C# 控制CH341进行SPI,I2C读写
    C# winform使用combobox遍历文件夹内所有文件
    通用分页存储过程
    如何让你的SQL运行得更快
    sql优化之使用索引
    SQL优化
    SQL 循环语句几种写法
  • 原文地址:https://www.cnblogs.com/ishell/p/4240146.html
Copyright © 2011-2022 走看看