- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我写了一个计算单词的程序。
这是程序
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
struct Entry {
word: String,
count: u32,
}
static SEPARATORS: &'static [char] = &[
' ', ',', '.', '!', '?', '\'', '"', '\n', '(', ')', '#', '{', '}', '[', ']', '-', ';', ':',
];
fn main() {
if let Err(err) = try_main() {
if err.kind() == std::io::ErrorKind::BrokenPipe {
return;
}
// Ignore any error that may occur while writing to stderr.
let _ = writeln!(std::io::stderr(), "{}", err);
}
}
fn try_main() -> Result<(), std::io::Error> {
let mut words: HashMap<String, u32> = HashMap::new();
let stdin = io::stdin();
for result in stdin.lock().lines() {
let line = result?;
line_processor(line, &mut words)
}
output(&mut words)?;
Ok(())
}
fn line_processor(line: String, words: &mut HashMap<String, u32>) {
let mut word = String::new();
for c in line.chars() {
if SEPARATORS.contains(&c) {
add_word(word, words);
word = String::new();
} else {
word.push_str(&c.to_string());
}
}
}
fn add_word(word: String, words: &mut HashMap<String, u32>) {
if word.len() > 0 {
if words.contains_key::<str>(&word) {
words.insert(word.to_string(), words.get(&word).unwrap() + 1);
} else {
words.insert(word.to_string(), 1);
}
// println!("word >{}<", word.to_string())
}
}
fn output(words: &mut HashMap<String, u32>) -> Result<(), std::io::Error> {
let mut stack = Vec::<Entry>::new();
for (k, v) in words {
stack.push(Entry {
word: k.to_string(),
count: *v,
});
}
stack.sort_by(|a, b| b.count.cmp(&a.count));
stack.reverse();
let stdout = io::stdout();
let mut stdout = stdout.lock();
while let Some(entry) = stack.pop() {
writeln!(stdout, "{}\t{}", entry.count, entry.word)?;
}
Ok(())
}
它将一些任意文本文件作为输入并计算单词以产生一些输出,如:
15 the
14 in
11 are
10 and
10 of
9 species
9 bats
8 horseshoe
8 is
6 or
6 as
5 which
5 their
我是这样编译的:
cargo build --release
我是这样运行的:
cat wiki-sample.txt | ./target/release/wordstats | head -n 50
我使用的 wiki-sample.txt 文件是 here
我将执行时间与 python (3.8) 版本进行了比较:
import sys
from collections import defaultdict
# import unidecode
seps = set(
[
" ",
",",
".",
"!",
"?",
"'",
'"',
"\n",
"(",
")",
"#",
"{",
"}",
"[",
"]",
"-",
";",
":",
]
)
def out(result):
for i in result:
print(f"{i[1]}\t{i[0]}")
if __name__ == "__main__":
c = defaultdict(int)
for line in sys.stdin:
words = line.split(" ")
for word in words:
clean_word = []
for char in word:
if char not in seps and char:
clean_word.append(char)
r = "".join(clean_word)
# r = unidecode.unidecode(r)
if r:
c[r] += 1
r = sorted(list(c.items()), key=lambda x: -x[1])
try:
out(r)
except BrokenPipeError as e:
pass
我是这样运行的:
cat /tmp/t.txt | ./venv/bin/python3 src/main.py | head -n 100
问题:Rust 的性能“仅”提高 ~3-4 倍是否正常?
我还想知道我是否在这里遗漏了什么,因为我发现“仅”100Mb 数据的计算时间相当长。我不认为(天真地)有一些低大 O 的处理,我可能是错的。
我习惯于将一些 python 代码与 go、java 或 vlang 中的一些等效代码进行比较,对于这些工作台,我经常有大约 20 倍到 100 倍的因数速度。
也许 cpython 擅长这种处理,也许我在 rust 程序中遗漏了一些东西(我对 rust 很陌生)以使其更高效。
我很害怕在我的测试中错过一些重要的东西,但是有没有想过这个?
编辑:按照人们的建议,我现在有以下版本:
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
struct Entry<'a> {
word: &'a str, // word: String,
count: u32,
}
static SEPARATORS: &'static [char] = &[
' ', ',', '.', '!', '?', '\'', '"', '\n', '(', ')', '#', '{', '}', '[', ']', '-', ';', ':',
];
fn main() {
if let Err(err) = try_main() {
if err.kind() == std::io::ErrorKind::BrokenPipe {
return;
}
// Ignore any error that may occur while writing to stderr.
let _ = writeln!(std::io::stderr(), "{}", err);
}
}
fn try_main() -> Result<(), std::io::Error> {
let mut words: HashMap<String, u32> = HashMap::new();
let stdin = io::stdin();
for result in stdin.lock().lines() {
let line = result?;
line_processor(line, &mut words)
}
output(&mut words)?;
Ok(())
}
fn line_processor(line: String, words: &mut HashMap<String, u32>) {
let mut l = line.as_str();
loop {
if let Some(pos) = l.find(|c: char| SEPARATORS.contains(&c)) {
let (head, tail) = l.split_at(pos);
add_word(head.to_owned(), words);
l = &tail[1..];
} else {
break;
}
}
}
fn add_word(word: String, words: &mut HashMap<String, u32>) {
if word.len() > 0 {
let count = words.entry(word).or_insert(0);
*count += 1;
}
}
fn output(words: &mut HashMap<String, u32>) -> Result<(), std::io::Error> {
let mut stack = Vec::<Entry>::new();
for (k, v) in words {
stack.push(Entry {
word: k.as_str(), // word: k.to_string(),
count: *v,
});
}
stack.sort_by(|a, b| a.count.cmp(&b.count));
let stdout = io::stdout();
let mut stdout = stdout.lock();
while let Some(entry) = stack.pop() {
writeln!(stdout, "{}\t{}", entry.count, entry.word)?;
}
Ok(())
}
现在在我的电脑上大约需要 2.6'。这比 python 版本好得多,快了将近 10 倍,后者非常好,但仍然不是我所期望的(这不是真正的问题)。可能还有其他一些我暂时没有想到的优化。
最佳答案
您可以通过避免 UTF-8 验证来加快搜索速度,并通过使用 bstr
crate 使您的搜索更智能一些。
use std::io;
use std::io::prelude::*;
use bstr::{BStr, BString, io::BufReadExt, ByteSlice};
type HashMap<K, V> = fnv::FnvHashMap<K, V>;
#[derive(Debug)]
struct Entry<'a> {
word: &'a BStr,
count: u32,
}
static SEPSET: &'static [u8] = b" ,.!?'\"\n()#{}[]-;:";
fn main() {
if let Err(err) = try_main() {
if err.kind() == std::io::ErrorKind::BrokenPipe {
return;
}
// Ignore any error that may occur while writing to stderr.
let _ = writeln!(std::io::stderr(), "{}", err);
}
}
fn try_main() -> Result<(), std::io::Error> {
let mut words: HashMap<BString, u32> = HashMap::default();
io::stdin().lock().for_byte_line(|line| {
line_processor(line, &mut words);
Ok(true)
})?;
output(&mut words)?;
Ok(())
}
fn line_processor(mut line: &[u8], words: &mut HashMap<BString, u32>) {
loop {
if let Some(pos) = line.find_byteset(SEPSET) {
let (head, tail) = line.split_at(pos);
add_word(head, words);
line = &tail[1..];
} else {
break;
}
}
}
fn add_word(word: &[u8], words: &mut HashMap<BString, u32>) {
if word.len() > 0 {
// The vast majority of the time we are looking
// up a word that already exists, so don't bother
// allocating in the common path. This means the
// uncommon path does two lookups, but it's so
// uncommon that the overall result is much faster.
if let Some(count) = words.get_mut(word.as_bstr()) {
*count += 1;
} else {
words.insert(BString::from(word), 1);
}
}
}
fn output(words: &mut HashMap<BString, u32>) -> Result<(), std::io::Error> {
let mut stack = Vec::<Entry>::new();
for (k, v) in words {
stack.push(Entry {
word: k.as_bstr(),
count: *v,
});
}
stack.sort_by(|a, b| a.count.cmp(&b.count));
let stdout = io::stdout();
let mut stdout = stdout.lock();
while let Some(entry) = stack.pop() {
writeln!(stdout, "{}\t{}", entry.count, entry.word)?;
}
Ok(())
}
此时,程序的大部分时间都花在了hashmap查找上。 (这就是为什么我改用上面的 fnv
的原因。)所以在这一点上让它更快可能意味着使用不同的策略来维护单词映射。我的猜测是大多数单词的长度只有几个字节,因此您可以对这些单词进行特殊处理,以使用数组作为映射而不是 HashMap 。它可能会大大加快速度,但也会使您的原始程序更加复杂。
至于这个速度是否符合预期,我会说,“我觉得差不多。”您的程序正在对 1450 万字的文档中的每个字执行一个操作。上面的程序在我的机器上大约需要 1.7 秒,这意味着它每秒处理大约 830 万个单词,或者每微秒大约 8.3 个单词。这似乎是正确的,因为每个词都会进行哈希查找并需要搜索才能找到下一个词。
关于python - Rust vs python 程序性能结果问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65782157/
我是 Mercurial 的新手,并且不知何故仍处于评估过程中,所以这四个概念对我来说有点困惑。有些被提到等同于 Git 的 Staging/Index 概念,有些甚至比 Git 的 Staging
关闭。这个问题需要更多focused .它目前不接受答案。 想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post . 6 个月前关闭。 Improve this ques
任何人都可以给我详细信息吗? 例如? #ID 是属性、特性、选择器还是 anchor ? 默认属性和默认属性是不同的东西吗? 这些都是标签还是元素? 我们将对此说些什么 这个 ..... 还有这些
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 8 年前。 Improve this qu
我有一个由 Javascript 填充的下拉列表。 在决定加载时显示的默认值时,我意识到以下属性显示的值完全相同: innerText innerHTML label text textContent
我可以知道每个 Exec 之间有什么区别吗? , ExecWait , ExecShell , nsExec::Exec , nsExec::ExecToLog, nsExec::ExecToStac
当您处于版本 1 和版本 2 之间时,您会如何维护您的软件? 从我的角度来看,“补丁”、“修补程序”、“维护版本”、“服务包”等术语都很模糊,根据与您交谈的对象不同,定义也不同。 您如何称呼版本之间的
我刚刚发现在 ES6 中有一个新的数学方法:Math.trunc . 我在 MDN article 中阅读了它的描述。 , 听起来像使用 |0 . 此外,>0 , &-1 , ^0也做类似的事情(感谢
我想知道我的 StackPanel 所有项目的高度。 有什么区别: Height - 获取或设置元素的建议高度。 ActualHeight - 获取该元素的渲染高度。 (只读) ExtentHeigh
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 9 年前。 Improve this
我对所有声称以某种方式阻止计算的内置 Mathematica 函数感到困惑:Unevaluated、Defer、Hold ,以及超过 6 个 Hold* 形式。 Mathematica 文档只是单独解
我什至不确定正确的术语,所以让我从我的目标开始:拥有一个简单的应用程序(“Data Doler”),它只会将大量数据从文件读取到内存中,然后提供服务将该数据切片到名为“Data Lapper”的单个多
我刚刚开始在我的项目中使用 Elasticsearch,我想像 sql 关键字一样搜索 '喜欢%' 做。 谁能解释一下 之间的区别通配符 , 前缀 , 查询字符串和 正则表达式 ? 哪个可以搜索最好性
由于我对任何主流浏览器(Firefox、Chrome、Opera)都不太满意,而且我尝试过的不太受欢迎的浏览器(近十几种)都没有,所以我决定 DIY 并制作一个网页我想要最好的浏览器。 主要目标是让它
我知道如何使用 Python 解析页面。我的问题是哪种方法是所有解析技术中最快的,其他方法的速度有多快? 我知道的解析技术有Xpath、DOM、BeautifulSoup,还有使用Python的fin
我试图从正在解析的命令行中找出哪个函数最适合将十进制、十六进制或八进制数转换为 int 最好——在不知道输入的情况下事先。 目标是使用一个函数来识别不同类型的输入并将其分配给它的整数 (int) 值,
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我们需要在我们的网站上显示酒吧、餐馆和剧院等各种场所的元信息(例如,地址、姓名)。 理想情况下,用户会输入地点名称以及邮政编码,我们会提供最接近的匹配项。 人们将哪些 API 用于类似的地理定位目的?
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我正在创建我的第一个 Web 应用程序,我真的很困惑应该使用什么技术。 我的应用程序需要看起来很严肃(像一个应用程序),它不需要很多色彩缤纷的图形界面。它只需要一个工具栏、一个标签栏、一个拆分面板(最
我是一名优秀的程序员,十分优秀!