统计一个文件的单词的个数(2)

 

上一个程序的效率太低了,统计一个5M的文件就3S以上,改进后,1S左右,

但是效率还是不行,用C写的比这个快多了,200ms。只是fgets()函数有点问题。

用intel的工具分析,是在getline()这个函数里花了大部分时间。悲剧的C++

 

#include <iostream> #include <fstream> #include <sstream> #include <string> #include <windows.h> #pragma comment(lib,"winmm.lib") //timeGetTime()函数用到的库 using namespace std; int main() { ifstream infile; DWORD start, end; string filename; cout << "请输入文件名:(注意要带扩展名的,如data1.txt) "; cin >> filename; infile.open(filename.c_str()); string line; size_t even_sum = 0; size_t odd_sum = 0; start = timeGetTime(); while (getline(infile,line)) { int i = 0; int j(0); int l = line.length(); while(line[i] == ' ' && i<l) ++i; while(i<l ) { int j = 0; while(line[i] != ' ' && i<l) { ++i; ++j; } if(j%2) ++even_sum; else ++odd_sum; while(line[i] == ' ' &&i<l) ++i; } } end = timeGetTime(); cout<<"time is:"<<end-start<<endl; infile.close(); cout<<"the sum of even number is:"<<even_sum<<endl<<"the sum of odd number is:"<<odd_sum<<endl; cout<<"the total sum is:"<<even_sum+odd_sum<<endl; // system("pause"); return 0; } //#include <stdio.h> //void main() //{ // int num=0,i=0;//num用于统计单词个数 // char str[100],c;//str[100]用存储输入的字符 // printf("请输入一个字符串:"); // gets(str);//获取输入的字符,存放在str[100]数组中 // do{ // while((c=str[i])==' ') // i++;//去掉第一个单词前的空格 // // if(c!='/0') // num++;//统计单词的个数 // // while((c=str[i])!=' '&&c!='/0') // i++;//去掉每个单词之间的空格 // }while(c!='/0');//判断是否为空格 // // printf("单诩的个数为:%d/n",num); // //} 

上一篇:VC++中的Dlg,App,Doc,view


下一篇:统计一个文件的单词的个数