用 C++ 写了个简单的词频统计,为啥比 DuckDB 还慢一半呢。。
步骤
- 生成 1亿 个长度为 15 的随机字符串(为了 SSO 优化)。内容是 1~1KW 的随机数字,并补足前导 0。
- 用
DuckDB统计前 1000 的高频词,用时 20 秒。 - 自己写个 C++ 程序,统计高频词,用时 30 秒。
- 改为生成长度为 16 的随机字符串,再用刚写的 C++ 程序统计,用时 40 秒。。
截图

C++ 代码
#include <queue>
#include <string>
#include <vector>
#include <iostream>
#include "ankerl/unordered_dense.h"
const auto TOP_NUM = 1000;
int main() {
std::cin.tie(nullptr);
std::ios::sync_with_stdio(false);
std::string word;
ankerl::unordered_dense::map<std::string, size_t> dict;
dict.reserve(10000000);
// 逐词计算频次
while (std::cin >> word)
++dict[word];
using dict_item_type = decltype(dict)::value_type;
auto comp = [](const auto* lhs, decltype(lhs) rhs) {
return lhs->second > rhs->second;
};
std::priority_queue<
const dict_item_type*,
std::vector<const dict_item_type*>,
decltype(comp)> words(comp);
// 找出排名靠前的词频
for (const auto& item: dict) {
if (words.size() < TOP_NUM)
words.push(&item);
else if (item.second > words.top()->second) {
words.pop();
words.push(&item);
}
}
// 并排序好这些高频词
std::deque<const dict_item_type*> result;
while (!words.empty()) {
auto top = words.top();
result.push_front(top);
words.pop();
}
// 再逐一输出
for (auto&& i: result)
std::cout << i->second << '\t' << i->first << '\n';
}


