gpt4 book ai didi

ruby - 为什么我的 rust 程序比 ruby​​ 程序慢?

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:42 27 4
gpt4 key购买 nike

<分区>

我用 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 要点:https://gist.github.com/Valve/533e0e22ae427d9ce440

Rust 要点: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 倍,但仍然只比 ruby​​ 版本快 4 倍。我想这是现​​在的文件系统限制。

文件的大小是:在我的机器上是 235886 行。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com