Search code examples
c++cmmap

Difference results with mmap (c), fopen(c) and ifstream(c++)


I have 3 different programs (mmap,fopen,ifstream) to count the occurance of a character in a file. I do this to test the performance of different techniques of file reading from the memory. But even though i get the same count for ifstream and fopen, mmap gives a higher count than the other two and i couldn't detect why.

ifstream:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <time.h>

using namespace std;

int main(){

printf("\n");

clock_t begin = clock();

ifstream file;
string filename = "loremipsum.txt";
file.open(filename.c_str());


char ch;
int count = 0;

while(file.get(ch)){

    if(ch == 'a'){
        count++;
    }
}

clock_t end = clock();



double time_spent = 0.0;
time_spent += (double)(end - begin) / CLOCKS_PER_SEC;

cout << "Number of 'a' in file: " << count << endl;
cout << "Time elapsed for counting: " << time_spent << endl;

printf("\n");

return 0;
}

fopen:

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 
#include <sys/stat.h>
#include <fcntl.h>


int main(void)
{
printf("\n");

FILE *fp;
int id;
char ch;
double time_spent = 0.0;
int count = 0;

clock_t begin = clock();
if ((fp = fopen ("loremipsum.txt", "r")) == NULL) {
    printf("Dosya açma hatası!");
    exit(1);
}

ch = fgetc ( fp ) ;



while(ch != EOF){

  
    if(ch == 'a'){
        count += 1;
    }

    ch = fgetc ( fp ) ;
}

clock_t end = clock();






time_spent += (double)(end - begin) / CLOCKS_PER_SEC;

printf("Time elapsed is %f seconds\n", time_spent);

printf("number of character 'a' is %d\n", count);
fclose(fp);

printf("\n");
return 0;
}

mmap:

#include <iostream>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h> 
#include <unistd.h>


int main(void){


int fd = open ("loremipsum.txt", O_RDONLY);
struct stat s;
size_t size;
int status = fstat(fd, &s);
size = s.st_size;
double time_spent = 0.0;

clock_t begin = clock();

char *ptr = (char*) mmap(0,size,PROT_READ,MAP_PRIVATE,fd,0);

if(ptr == MAP_FAILED){

    printf("Mapping failed\n");
    return 1;
}



int i = 0, count = 0;
while(ptr[i] != EOF){
    if(ptr[i] == 'a'){
        count++;
    }
    i++;
}

clock_t end = clock();


printf("\nnumber of a is %d\n", count);

time_spent += (double)(end - begin) / CLOCKS_PER_SEC;

printf("Time elapsed is %f seconds\n", time_spent);


status = munmap(ptr, size);

if(status != 0){
    
    printf("Unmapping failed\n");
    return 1;
}
close(fd);

printf("\n");
return 0;


}

Solution

  • In the mmap version the ptr[i] != EOF check looks highly suspicious, the loop should be changed to a for-loop that always iterates exactly size times because ptr[i] can legitimately be any byte value, and there is no way it can signal EOF.