提问者:小点点

mmap(c),fopen(c)和ifstream(c++)的差异结果


我有3个不同的程序(mmape,fopen,ifstream)来计算文件中字符的出现次数。我这样做是为了测试从内存读取文件的不同技术的性能。但是,即使我为ifstream和fopen获得了相同的计数,mmap给出的计数比其他两个高,我也不知道为什么。

如果流:

#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;


}

共1个答案

匿名用户

在mmap版本中,检查看起来非常可疑,应该将循环更改为次数,因为可以合法地为任何字节值,而且它不可能发送信号给

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(mmap|c|fopen|c|ifstream|c++|差异)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?