天天看點

統計一個檔案的單詞的個數(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)

}

}

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

//

//} 

繼續閱讀