Monday, August 28, 2006

Mapping a File to Memory

Finally, we use the mmap(2) call to map the file to the memory area and then read the elements of the array directly from the memory, bypassing the I/O calls. We can see that this approach is orders of magnitude more efficient for both forward and backward sequential reading of the file. Replacing the I/O operations with mmap calls should always be considered for applications that perform frequent I/O operations.

/* example_mmap.c
cc example_mmap.c -o example_mmap */
#include
#include
#define N 1000000
FILE *example_file;
int x[N], i;
hrtime_t st, et;
float secs;

int main() {
create_file();
read_file_mmap();
return 0;
}
#include

int read_file_mmap(){
char *example_map;
int offset;
if( (example_file = fopen( "ex_file", "r" )) == NULL ){
printf( "Problem opening the file\n" ); return -1; }
st= gethrtime();
example_map=mmap(NULL,N*sizeof(int),PROT_READ,
MAP_SHARED,fileno(example_file),0);
offset = 0;
for ( i = 0; i < N; i++){
x[i] = *(int*)(&example_map[offset]);
offset = offset + sizeof(int);
}
et= gethrtime();
secs = (( float) (et-st) / (float) 1000000000);
printf( "x[11111] = %ld \n", x[11111] );
printf(" RUNTIME (mmap): %6.4f Seconds \n", secs);
fclose(example_file);

if( (example_file = fopen( "ex_file", "r" )) == NULL ){
printf( "Problem opening the file\n" ); return -1; }
st= gethrtime();
example_map=mmap(NULL,N*sizeof(int),PROT_READ,
MAP_SHARED,fileno(example_file),0);
offset = (N-1)*sizeof(int);
for ( i = N-1; i >= 0; i--){
x[i] = *(int*)(&example_map[offset]);
offset = offset - sizeof(int);
}
et= gethrtime();
secs = (( float) (et-st) / (float) 1000000000);
printf( "x[11111] = %ld \n", x[11111] );
printf(" RUNTIME (mmap): %6.4f Seconds \n", secs);
fclose(example_file);

return 0;
}

No comments: