我在Ruby和Rust中编写了一个anagram finder,并且发现Rust程序的速度几乎是Ruby版本的2倍。
Ruby版本:
source = ARGV.first
sorted_source = source.chars.sort.join
anagrams = Hash.new
File.open('/usr/share/dict/words') do |f|
f.each_line do |l|
word = l.chomp
sorted_word = word.chars.sort.join
if anagrams[sorted_word]
anagrams[sorted_word] << word
else
anagrams[sorted_word] = [word]
end
end
end
found = anagrams[sorted_source]
puts found
Rust版本:
use std::os;
use std::io::{File, BufferedReader};
use std::collections::HashMap;
fn main(){
let path = Path::new("/usr/share/dict/words");
match File::open(&path) {
Err(e) => println!("Error opening file: {}", e.desc),
Ok(f) => {
let mut anagrams: HashMap<String, Vec<String>> = HashMap::new();
let mut reader = BufferedReader::new(f);
for maybe_line in reader.lines() {
let word = maybe_line.unwrap().as_slice().trim_chars('\n').to_string();
let mut chars: Vec<char> = word.as_slice().chars().collect();
chars.sort();
let sorted_word = String::from_chars(chars.as_slice());
if anagrams.contains_key(&sorted_word) {
anagrams.get_mut(&sorted_word).push(word);
} else {
anagrams.insert(sorted_word, vec!(word));
}
}
let args = os::args();
if args.len() == 2 {
let source = args[1].clone();
let mut chars: Vec<char> = source.as_slice().chars().collect();
chars.sort();
let sorted_word = String::from_chars(chars.as_slice());
match anagrams.find(&sorted_word) {
Some(anagrams) => println!("{}", anagrams),
None => println!("No anagrams found")
}
} else {
println!("Call the app with exactly 1 argument, the word to find anagrams for");
}
}
}
}
结果:
time ruby anagram.rb horse
horse
shoer
shore
ruby anagram.rb horse 1.69s user 0.12s system 99% cpu 1.812 total
time ./anagram horse
[horse, shoer, shore]
./anagram horse 3.02s user 0.05s system 99% cpu 3.080 total
ruby -v
ruby 2.1.3p242(2014-09-19修订版47630)[x86_64-darwin13.0]
rustc --version
rustc 0.13.0-nightly(172b59abe 2014-10-25 00:32:07 +0000)
Ruby gist:https://gist.github.com/Valve/533e0e22ae427d9ce440
Rust gist:https://gist.github.com/Valve/834917941b00668478f2
更新:
正如Francis Gagne所说,我用-O标志编译了它:
time ./anagram horse
[horse, shoer, shore]
./anagram horse 0.37s user 0.05s system 96% cpu 0.429 total
速度增加了8倍,但仍然比红宝石版快4倍。 我想现在这是一个文件系统限制。
文件大小为:我机器上的235886行。
答案 0 :(得分:3)
如果您使用的是货物,则可以将优化设置为高于-O
。
在Cargo.toml
。
[package]
name = "anagram"
version = "0.1.0"
authors = ["Your name here <Your email here>"]
[profile.release]
opt-level = 3
并运行Cargo build --release
。完成后,运行time ./anagram horse