我需要計算104gb文件中字符串"<page>"
的出現次數,以獲取給定Wikipedia轉儲中的文章數量。首先,我已經試過了。如何加速計算大文件中單詞的出現次數?
grep -F '<page>' enwiki-20141208-pages-meta-current.xml | uniq -c
但是,一段時間後,grep崩潰了。所以我寫了下面的程序。但是,它只處理我機器上20mb/s的輸入文件,這大約是我硬盤5%的工作量。我怎樣才能加快這個代碼?
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// Open up file
std::ifstream in("enwiki-20141208-pages-meta-current.xml");
if (!in.is_open()) {
std::cout << "Could not open file." << std::endl;
return 0;
}
// Statistics counters
size_t chars = 0, pages = 0;
// Token to look for
const std::string token = "<page>";
size_t token_length = token.length();
// Read one char at a time
size_t matching = 0;
while (in.good()) {
// Read one char at a time
char current;
in.read(¤t, 1);
if (in.eof())
break;
chars++;
// Continue matching the token
if (current == token[matching]) {
matching++;
// Reached full token
if (matching == token_length) {
pages++;
matching = 0;
// Print progress
if (pages % 1000 == 0) {
std::cout << pages << " pages, ";
std::cout << (chars/1024/1024) << " mb" << std::endl;
}
}
}
// Start over again
else {
matching = 0;
}
}
// Print result
std::cout << "Overall pages: " << pages << std::endl;
// Cleanup
in.close();
return 0;
}
沒有問題,但你應該讀作[「爲什麼是的iostream :: EOF算錯了?一個循環條件中」(http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside -a循環條件考慮的,是錯誤的)。 –
一次讀一行可能比某個時候的角色要好。我假設你正在測試這個優化版本,如果不是你應該的。 –
@CaptainObvlious謝謝,修正。 – danijar