mmap的性能

  mmap操作提供了一种机制,让用户程序直接访问设备内存,这种机制,相比较在用户空间和内核空间互相拷贝数据,效率更高。在要求高性能的应用中比较常用。mmap映射内存必须是页面大小的整数倍,面向流的设备不能进行mmap,mmap的实现和硬件有关。(百度百科)

      下面的实例来自网络,简单修改了一下,比较了传统的OPEN/WRITE与mmap的性能,网上有很多原理分析,就不赘述了。 

 1 #include<unistd.h> 
2
#include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<sys/types.h> 6 #include<sys/stat.h> 7 #include<sys/time.h> 8 #include<fcntl.h> 9 #include<sys/mman.h> 10 11 #define MAX 1000 12 13 int main() 14 { 15 int i=0; 16 int count=0, fd=0; 17 struct timeval tv1, tv2; 18 int *array = (int *)calloc( MAX,sizeof(int)); 19 int *pmmap =NULL; 20 /*create*/ 21 22 fd = open( "mmap_test", O_CREAT ); 23 write( fd, (void *)array, sizeof(int)*MAX ); 24 close (fd); 25 /*mmap*/ 26 gettimeofday( &tv1, NULL );//获得微秒级时间 27 fd = open( "mmap_test", O_RDWR ); 28 pmmap = mmap( NULL, sizeof(int)*MAX, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 ); 29 munmap( pmmap, sizeof(int)*MAX );31 close( fd ); 32 gettimeofday( &tv2, NULL ); 33 printf( "Time of mmap: %dms\n", tv2.tv_usec-tv1.tv_usec ); 34 35 /*read*/ 36 gettimeofday( &tv1, NULL ); 37 fd = open( "mmap_test", O_RDWR); 38 if( sizeof(int)*MAX != read( fd, (void *)array, sizeof(int)*MAX ) ) 39 { 40 printf( "Reading data failed...\n" ); 41 return -1; 42 } 43 44 if( sizeof(int)*MAX != write( fd, (void *)array, sizeof(int)*MAX ) ) 45 { 46 printf( "Writing data failed...\n" ); 47 return -1; 48 } 49 free( array ); 50 close( fd ); 51 gettimeofday( &tv2, NULL ); 52 printf( "Time of read/write: %dms\n", tv2.tv_usec-tv1.tv_usec ); 53 54 55 return 0; 56 }

 

posted @ 2016-04-22 15:17  still_waters  阅读(957)  评论(0编辑  收藏  举报